繁体   English   中英

如何使用 setInterval 重启关键帧 animation?

[英]How to restart a keyframe animation with setInterval?

我一直在努力寻找问题的答案,但始终找不到。
我希望能够在完成后清除间隔,但随后能够重新启动它。
我当前的代码不允许我这样做:一旦间隔停止,您就无法再次运行它。
这是我的代码:

 function about() { var about = document.getElementById("about") about.classList.add("about-mi") var moreinfo = setInterval (function() { about.classList.remove("about-mi") }, 2000) clearInterval(moreinfo) }
 .about-mi { animation-name: moreinfo; animation-duration: 2s; } @keyframes moreinfo { 0% {color: black;} 50% {color: red; transform: translateY(-20px);} 100% {color: black;} }
 <a onclick="about()">▼</a> <h2 id=about>About</h2>

我更喜欢只需要 HTML、CSS 或 JavaScript 的解决方案,但我也愿意尝试需要 jQuery 的解决方案。

实际上setInterval在这里没有做任何事情。 您不需要为此使用 interval ,只需使用setTimeout

 function about() { var about = document.getElementById("about") about.classList.add("about-mi") var moreinfo = setTimeout(function() { about.classList.remove("about-mi") }, 2000) }
 .about-mi { animation-name: moreinfo; animation-duration: 2s; } @keyframes moreinfo { 0% { color: black; } 50% { color: red; transform: translateY(-20px); } 100% { color: black; } }
 <a onclick="about()">▼</a> <h2 id=about>About</h2>

你也可以只用 CSS 做到这一点

 .about-mi { animation: moreinfo 2s, reset 2.1s; } a:active+.about-mi { animation: anything, reset 2.1s; } @keyframes moreinfo { 0% { color: black; } 50% { color: red; transform: translateY(-20px); } 100% { color: black; } } @keyframes reset { from, to { color: black; transform: unset; } }
 <p>Wait for the animation to finish before first clicking (2.1s). because the animation starts when the page loads.</p> <a href="#">▼</a> <h2 id="about" class="about-mi">About</h2>

当您使用间隔超时删除 class about-mi以匹配您在 css 中定义的2 seconds时, animation-duration: 2s; 当您开始更改其中一个值时,很难保持,您始终要记住哦哦,我还必须更新另一个值,比如javascript valuecss value

鉴于此,在这种情况下,另一种方法是删除基于HTMLElement: animationend事件的 class,如下所示:

 var aboutElement = document.getElementById("about") function about() { aboutElement.classList.add("about-mi") } aboutElement.addEventListener("animationend", function(){ aboutElement.classList.remove("about-mi"); });
 .about-mi { animation-name: moreinfo; animation-duration: 2s; } @keyframes moreinfo { 0% {color: black;} 50% {color: red; transform: translateY(-20px);} 100% {color: black;} }
 <a onclick="about()">▼</a> <h2 id=about>About</h2>

在您的具体情况下,看起来您只需要运行代码一次,而不是每隔一段时间运行多次,所以正如@dgknca 提到的那样,您只需要一个setTimeout


一般如何重新开始间隔

回答这个问题以防其他用户看到这篇文章。 你能做的最好的事情(据我所知)是用你想要的功能定义一个非匿名的 function ,然后在间隔中使用它:

function doSomething() {
    // your logic here
    console.log('I am doing something.');
}

// execute doSomething every 1 second
var interval = setInterval(doSomething, 1000);

像这样,您可以使用以下方法取消间隔:

clearInterval(interval);

要“重新启动”间隔,您需要将interval分配给新间隔:

interval = setInterval(doSomething, 1000);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM