javascript - JS setTimeout 每隔一段时间添加/删除类

标签 javascript html css arrays json

我有一个脚本,每 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/

相关文章:

html - 我的 iPhone 6 上的 Safari 忽略了 overflow-x : hidden

javascript - 使用 CSS 或 javascript/jQuery,我应该使用哪种方法使我网站的导航栏看起来更像 3d 风格?

javascript - Reactjs .NET 中的函数永远无法实现 - 如何在渲染中调用简单的箭头函数?

javascript - 未捕获的类型错误 : Cannot read property '$bvModal' of undefined vue

javascript - 如何让 Javascript 图像幻灯片缓慢改变图像?

html - 如何使列末尾的内容具有 100% 的高度可滚动?

html - 缩小时文本变长

javascript - jQuery 代码在 Chrome 中有效但在 IE 中无效

javascript - Angular 2 - 预加载背景图片?

javascript - Dojo 工具包 - 如何使用函数覆盖 css?