Javascript 在 CSS3 中重新启动动画:还有比移除元素更好的方法吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6268508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:02:14  来源:igfitidea点击:

Restart animation in CSS3: any better way than removing the element?

javascriptcss

提问by Leo

I have a CSS3 animation that needs to be restarted on a click. It's a bar showing how much time is left. I'm using the scaleY(0) transform to create the effect.

我有一个需要在单击时重新启动的 CSS3 动画。这是一个显示剩余时间的条形图。我正在使用 scaleY(0) 变换来创建效果。

Now I need to restart the animation by restoring the bar to scaleY(1) and let it go to scaleY(0) again. My first attempt to set scaleY(1) failed because it takes the same 15 seconds to bring it back to full length. Even if I change the duration to 0.1 second, I would need to delay or chain the assignment of scaleY(0) to let the bar replenishment complete. It feels too complicated for such a simple task.

现在我需要通过将条恢复到 scaleY(1) 并让它再次转到 scaleY(0) 来重新启动动画。我第一次尝试设置 scaleY(1) 失败了,因为它需要同样的 15 秒才能恢复到全长。即使我将持续时间更改为 0.1 秒,我也需要延迟或链接 scaleY(0) 的分配以让 bar 补货完成。这么简单的任务,感觉太复杂了。

I also found an interesting tip to restart the animation by removing the element from the document, and then re-inserting a clone of it: http://css-tricks.com/restart-css-animation/

我还发现了一个有趣的技巧,可以通过从文档中删除元素来重新启动动画,然后重新插入它的一个副本:http: //css-tricks.com/restart-css-animation/

It works, but is there a better way to restart a CSS animation? I'm using Prototype and Move.js, but I'm not restricted to them.

它有效,但是有没有更好的方法来重新启动 CSS 动画?我正在使用 Prototype 和Move.js,但我不限于它们。

回答by Lea Verou

Just set the animationproperty via JavaScript to "none"and then set a timeout that changes the property to "", so it inherits from the CSS again.

只需animation通过 JavaScript将属性设置为"none",然后设置一个超时,将属性更改为"",因此它再次从 CSS 继承。

Demo for Webkit here: http://jsfiddle.net/leaverou/xK6sa/However, keep in mind that in real world usage, you should also include -moz- (at least).

此处为 Webkit 的演示:http: //jsfiddle.net/leaverou/xK6sa/但是,请记住,在实际使用中,您还应该包括 -moz-(至少)。

回答by user

No need in timeout, use reflowto apply the change:

不需要超时,使用回流来应用更改:

function reset_animation() {
  var el = document.getElementById('animated');
  el.style.animation = 'none';
  el.offsetHeight; /* trigger reflow */
  el.style.animation = null; 
}
#animated {
  position: absolute;
  width: 50px; height: 50px;
  background-color: black;
  animation: bounce 3s ease-in-out infinite;
}
@keyframes bounce {
  0% { left: 0; }
  50% { left: calc( 100% - 50px ); }
  100% { left: 0; }
}
<div id="animated"></div>
<button onclick="reset_animation()">Reset</button>

回答by Viktor Mezhenskyi

If you have some class for css3 animation, for exapmle .blinkthen you can removeClassfor some element and addClassfor this element thought setTimeoutwith 1 milisecond by click.

如果你有一些类CSS3动画,为exapmle .blink那么你可以removeClass一些元素和addClass这个元素想到的setTimeout与1个milisecond通过点击。

  $("#element").click(function(){
     $(this).removeClass("blink");

     setTimeout(function(){
       $(this).addClass("blink);
    },1 ///it may be only 1 milisecond, it's enough
  });

回答by bigjosh

  1. Implement the animation as a CSS descriptor
  2. Add the descriptor to an element to start the animation
  3. Use a animationendevent handler function to remove the descriptor when the animation completes so that it will be ready to be added again next time you want to restart the animation.
  1. 将动画实现为 CSS 描述符
  2. 将描述符添加到元素以开始动画
  3. 使用animationend事件处理函数在动画完成时移除描述符,以便下次您想要重新启动动画时再次添加它。

---HTML---

---HTML---

<div id="animatedText">
Animation happens here
</div>

<script>

  function startanimation(element) {

    element.classList.add("animateDescriptor");

    element.addEventListener( "animationend",  function() {

      element.classList.remove("animateDescriptor");    

    } );

  }

</script>


<button onclick="startanimation( document.getElementById('animatedText') )">
Click to animate above text
</button>

---CSS---

---CSS---

@keyframes fadeinout {  
      from { color: #000000; }  
    25% {color: #0000FF; }  
    50% {color: #00FF00; }      
    75% {color: #FF0000; }  
      to { color : #000000; }   
  } 

  .animateDescriptor {  
    animation: fadeinout 1.0s;  
  }     

Try it here:

在这里试试:

https://jsfiddle.net/bigjosh/avp9Lk6r/50/

https://jsfiddle.net/bigjosh/avp9Lk6r/50/

回答by Sava B.

There is an answer on MDN, which is similar to the reflow approach:

MDN上有一个答案,类似于reflow的做法:

<div class="box">
</div>

<div class="runButton">Click me to run the animation</div>
@keyframes colorchange {
  0% { background: yellow }
  100% { background: blue }
}

.box {
  width: 100px;
  height: 100px;
  border: 1px solid black;
}

.changing {
  animation: colorchange 2s;
}
function play() {
  document.querySelector(".box").className = "box";
  window.requestAnimationFrame(function(time) {
    window.requestAnimationFrame(function(time) {
      document.querySelector(".box").className = "box changing";
    });
  });
}

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Animations/Tips

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Animations/Tips

回答by Pall Arpad

Create a second "keyframe@" which restarts you animation, only problem with this you cannot set any animation properties for the restarting animation (it just kinda pops back)

创建第二个“关键帧@”来重新启动动画,唯一的问题是您无法为重新启动的动画设置任何动画属性(它只是有点弹出)

----- HTML -----

----- HTML -----

<div class="slide">
    Some text..............
    <div id="slide-anim"></div>
</div><br>
    <button onclick="slider()"> Animation </button>
    <button id="anim-restart"> Restart Animation </button>
<script>
    var animElement = document.getElementById('slide-anim');
    document.getElementById('anim-restart').addEventListener("mouseup", restart_slider);

    function slider() {
        animElement.style.animationName = "slider";             // other animation properties are specified in CSS
    }
    function restart_slider() {
        animElement.style.animation = "slider-restart";         
    }
</script>

----- CSS -----

----- CSS -----

.slide {
    position: relative;
    border: 3px black inset;
    padding: 3px;
    width: auto;
    overflow: hidden;
}
.slide div:first-child {
    position: absolute;
    width: 100%;
    height: 100%;
    background: url(wood.jpg) repeat-x;
    left: 0%;
    top: 0%;            
    animation-duration: 2s;
    animation-delay: 250ms;
    animation-fill-mode: forwards;
    animation-timing-function: cubic-bezier(.33,.99,1,1); 
}

@keyframes slider {
    to {left: 100%;}
}

@keyframes slider-restart {
    to {left: 0%;}
}

回答by Usama Majid

AoA

迎角

You can also use display property, just set the display to none.

您也可以使用 display 属性,只需将 display 设置为 none。

display:none;

and the change backs it to block.

并且更改支持它阻止。

display:block;

using JavaScript.

使用 JavaScript。

and it will work amazingly.

它会产生惊人的效果。

回答by Ron Cohen

on this page you can read about restart the element animation: https://css-tricks.com/restart-css-animation/here is my example:

在此页面上,您可以阅读有关重新启动元素动画的信息:https: //css-tricks.com/restart-css-animation/这是我的示例:

 <head>
        <style>
            @keyframes selectss
{
    0%{opacity: 0.7;transform:scale(1);} 
    100%{transform:scale(2);opacity: 0;}
}
        </style>
        <script>
            function animation()
            {
                var elm = document.getElementById('circle');
                elm.style.animation='selectss 2s ease-out';
                var newone = elm.cloneNode(true);
                elm.parentNode.replaceChild(newone, elm);
            }
        </script>
    </head>
    <body>
        <div id="circle" style="height: 280px;width: 280px;opacity: 0;background-color: aqua;border-radius: 500px;"></div>
        <button onclick="animation()"></button>
    </body>

but if you want to you can just remove the element animation and then return it:

但如果你愿意,你可以删除元素动画然后返回它:

function animation()
        {
            var elm = document.getElementById('circle');
            elm.style.animation='';
            setTimeout(function () {elm.style.animation='selectss 2s ease-out';},10)
        }

hope i helped!

希望我有所帮助!