我有一个脚本,每 6 秒打印一个新的数组元素。 现在我想为每个间隔添加一个类(Css 动画),然后将其删除。这样每个数字都会淡入(和淡出 - 这是在我的 CSS 动画中)。 我曾经尝试为整个 h2#quotes 制作动画 - 但它似乎与脚本/css 不协调。 这是一个实时示例:http://quotes.sumisuweb.at/
var quoteIndex = 0;
var quoteJson = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
var setQuote = function() {
var quote = quoteJson[quoteIndex];
quoteIndex = (quoteIndex + 1) % quoteJson.length;
setTimeout(setQuote, 6000);
$("#quote").text(quote);
}
jQuery( document ).ready(function($) {
setQuote();
});
CSS:
#quote {
text-shadow: 0px 0px 13px white;
text-align: center;
margin-top: 100px;
font-size: 100pt;
}
.animateQuote {
animation-name: fadeIn;
animation-duration: 6s;
animation-timing-function: linear;
}
@keyframes fadeIn {
0% {opacity: 0.0;}
80% {opacity: 1.0;}
100% {opacity: 0.0;}
}
最佳答案
我认为您不需要超时来添加/删除类。
您可以将动画设置为重复,然后在更新数字的同时启动动画。
更新的代码和更改注释:
编辑:修复了动画与超时不同步的错误。 从 here 修复和 here .
还制作了动画/超时 1 秒。所以更容易测试更多的迭代
var quoteIndex = 0;
var quoteJson = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
var $quote = null;
var setQuote = function() {
$quote[0].style.animation = 'none'; // remove the animation
void $quote[0].offsetWidth; // trigger reflow
$quote[0].style.animation = null; // add the animation back
var quote = quoteJson[quoteIndex];
quoteIndex = (quoteIndex + 1) % quoteJson.length;
$quote.text(quote);
setTimeout(setQuote, 1000); // needs to be same time as animation
}
jQuery( document ).ready(function($) {
$quote = $("#quote");
setQuote();
});
#quote {
text-shadow: 0px 0px 13px white;
text-align: center;
margin-top: 100px;
font-size: 100pt;
animation: fadeIn 1s linear infinite; /* needs to be same time as timeout */
}
@keyframes fadeIn {
0% {opacity: 0.0;}
80% {opacity: 1.0;}
100% {opacity: 0.0;}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="quote"></div>
关于javascript - JS setTimeout 每隔一段时间添加/删除类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47418368/