【问题标题】:Javascript, CSS, button doesn't call the function for an animation after first click [duplicate]首次单击后,Javascript,CSS,按钮不调用动画函数[重复]
【发布时间】:2018-08-11 11:55:34
【问题描述】:

有没有办法在不更改HTML代码的情况下,在第一次点击后多次调用函数动画?我需要保留代码中的 id 和 class。我试图将 display 属性设置为 none,但它似乎不起作用。我希望动画在单击<p> 标签时开始,但是一旦我第一次单击它,动画就不会再次开始。即使在动画中间,我也想再次调用该函数。我阅读了有关该主题的所有其他问题,但它们似乎对我不起作用,因为 HTML 不同。请不要使用Jquery,但可以使用普通的JS。谢谢!

     <!DOCTYPE html>
    <html>
   <head>
   <style>

 .something {
    background:blue;
    height:20px;
   width:20px;}
  .earth{
  position :relative;
    animation:move 10s linear;
  background:red;
  height:20px;
    width:20px;

         }
      @-webkit-keyframes move
     {
     from { left: 0%;  }
        to { left: 100%; }
      }

       </style>
      <script>
      function changetext (){

        document.getElementById("demo").style.color = "red";
      animation();
       }

        function animation(){
            document.getElementById('ghost').className ='earth';


        }
         function repeat(){
         var sd = document.getElementById("ghost").className ='earth';
        sd.style.display = 'none';
       }
     </script>
     </head>
       <body>
     <div class="something"></div>
      <div id="ghost"> </div>

      <p onclick="changetext();" id="demo"> HELLO WORLD </p>


     </body>
       </html>

【问题讨论】:

    标签: javascript css


    【解决方案1】:

    您可以删除该类并重新添加它,但会有 1 毫秒的轻微延迟。

    function changetext() {
      document.getElementById("demo").style.color = "red";
      animation();
    }
    
    function animation() {
      document.getElementById('ghost').className = '';
      setTimeout(function(){
        document.getElementById('ghost').className = 'earth';
      }, 1);
    }
    .something {
      background: blue;
      height: 20px;
      width: 20px;
    }
    
    .earth {
      position: relative;
      animation: move 10s linear;
      background: red;
      height: 20px;
      width: 20px;
    }
    
    @-webkit-keyframes move {
      from {
        left: 0%;
      }
      to {
        left: 100%;
      }
    <div class="something"></div>
    <div id="ghost"> </div>
    
    <p onclick="changetext();" id="demo"> HELLO WORLD </p>

    【讨论】:

    • 即使使用 0 而不是 1 也可以;)
    • 但是 1 看起来更好@TemaniAfif
    • 为什么更好? :)
    • 看起来更好..:P
    • @TemaniAfif 和 void 只是为了挑剔,但 setTimeout 的最小值无论如何都是4ms。此外,您可以通过强制回流来完全避免异步(ghost.offsetWidth; 会这样做)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2013-12-21
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    • 2019-10-04
    相关资源
    最近更新 更多