代码之家  ›  专栏  ›  技术社区  ›  swinn

从“none”更改元素的显示将重播其动画[重复]

  •  1
  • swinn  · 技术社区  · 8 年前

    观看下面的片段,您会注意到滑动动画在 .addClass 语句执行,第二次执行时 #test display 设置为 initial (超时设置有助于查看问题):

    $(() => {
      $('#test').addClass('animate');
    	
      setTimeout(() => {
        $('#test').css({ display: 'none' });
        setTimeout(() => {
          $('#test').css({ display: 'initial' });
        }, 1000);
      }, 1000);
    });
    #test {
      position: relative;
      left: 0;
    }
    
    #test.animate {
      animation: move 1s ease forwards;
    }
    
    @keyframes move {
      100% {
        left: 100px;
      }
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <img id="test" src="https://cdn4.buysellads.net/uu/1/3332/1524843316-62666.png">

    为什么要更改元素的 显示 属性来自 none 到一个可见的( 最初的 , block 等等)通过javascript会导致分配给元素的动画重播,我如何才能禁止它重播?

    注:有 animation-fill-mode 设置为 forwards 是一项要求。

    1 回复  |  直到 8 年前
        1
  •  1
  •   muecas    8 年前

    只需移除 animate 在第一个动画完成后初始化。

    $(() => {
      $('#test').addClass('animate');
    	
      setTimeout(() => {
        $('#test').addClass('pause').css({ display: 'none' });
        setTimeout(() => {
          $('#test').css({ display: 'initial' });
        }, 1000);
      }, 1000);
    });
    #test {
      visibility: hidden;
      position: relative;
      left: 0;
    }
    
    #test.animate {
      visibility: visible;
      animation: move 1s ease forwards;
    }
    
    #test.animate.pause {
      animation-play-state: paused;
    }
    
    @keyframes move {
      0% {
        display: none;
        left: 100px;
      }
      1% {
        display: inital;
        left: 0px;
      }
      100% {
        left: 100px;
      }
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <img id="test" src="https://cdn4.buysellads.net/uu/1/3332/1524843316-62666.png">