How to transition child when parent goes from display: none to block

前端 未结 4 2080
轻奢々
轻奢々 2021-02-13 15:55

I\'m having trouble creating a flyout menu with a specific effect. The flyout goes from display:none to block and then I use jquery to animate opacity from 0 to 1 (and vice vers

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-13 16:22

    @rodneyrehm's answer pretty much sums up everything you need when handling animations with css display property.

    You need to trigger a reflow after toggling the display property and apply an animation class after it.

    // find elements
    const banner = $("#banner")
    const button = $(".banner__button")
    const text = $(".banner__text")
    let isVisible = false
    
    // toggle display
    button.on("click", () => {
    	if (!isVisible) {
      	text.addClass("display--block")
        text.outerWidth()
        text.addClass("text--show")
        isVisible = true
      } else {
      	text.addClass("text--hide")
        .one('webkitAnimationEnd oanimationend msAnimationEnd animationend', () => {
      		text.removeClass("display--block")
          text.removeClass("text--show")
          text.removeClass("text--hide")
          isVisible = false
        })
      }
      
    })
    body {
      background: #20262E;
      padding: 20px;
      font-family: Helvetica;
    }
    
    #banner {
      background: #fff;
      border-radius: 4px;
      padding: 20px;
      font-size: 25px;
      text-align: center;
      margin: 0 auto;
      width: 300px;
      height: 150px;
      display: flex;
      flex-flow: column nowrap;
    }
    
    .banner__button {
      background: #0084ff;
      border: none;
      border-radius: 5px;
      padding: 8px 14px;
      font-size: 15px;
      color: #fff;
      cursor: pointer;
      transition: box-shadow 0.3s, transform 0.6s;
    }
    
    .banner__button:hover {
      box-shadow: 0 3px 8px 2px #9d9d91;
      transform: translateY(-2px)
    }
    
    .banner__button:focus {
      outline: 0;
    }
    
    .flex--1 {
      flex: 1;
    }
    
    .banner__text {
      display: none;
      opacity: 0;
      transition: all 0.6s;
    }
    
    .display--block {
      display: block;
    }
    .text--show {
      animation: slide-in 1s forwards;
    }
    .text--hide {
      animation: slide-out 1s forwards;
    }
    
    @keyframes slide-in {
      0% {
        opacity: 0;
        transform: translateX(-30px)
      }
      100% {
        opacity: 1;
        transform: translateX(0px)
      }
    }
    @keyframes slide-out {
      0% {
        opacity: 1;
        transform: translateX(0px)
      }
      100% {
        opacity: 0;
        transform: translateX(30px)
      }
    }
    
    

提交回复
热议问题