在setInterval问题中淡化动画(显示/隐藏)

时间:2018-01-18 10:32:28

标签: javascript jquery html web

我正在使用jQuery 3.2.1并尝试在我的目标网页上创建文本滑块。我想切换一些元素,这样一次只能看到一个元素,几秒后它会淡出,下一个元素(或第一个元素,如果没有)淡入。

问题是,经过几个循环(至少在chrome中),突然所有元素同时fadeIn和fadeOut同时出现。

这是我的HTML:

$('#animate-text h1').hide();
var currText = 0;
var texts = $('#animate-text h1');
var element = texts.eq(currText);
element.fadeIn(1000);

setInterval(function(){
    currText++;
    if(currText > texts.length-1) currText = 0;
    element.fadeOut(1000);
    setTimeout(function(){	
        element = texts.eq(currText);
        element.fadeIn(1000);
    },1000);
},3000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='animate-text'>
    <h1> text1 </h1>
    <h1> text2 </h1>
</div>

1 个答案:

答案 0 :(得分:1)

我添加了一个“停止”功能,api说

描述:停止匹配元素上当前正在运行的动画。

所以这种方式动画不应该叠加,至少在我的chrome中一切正常

$('#animate-text h1').hide();
var currText = 0;
var texts = $('#animate-text h1');
var element = texts.eq(currText);
element.fadeIn(1000);

setInterval(function(){
    currText++;
    if(currText > texts.length-1) currText = 0;
    element.fadeOut(1000);
    setTimeout(function(){	
        element = texts.eq(currText);
        element.stop(true,true)
        element.fadeIn(1000);
    },1000);
},3000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='animate-text'>
    <h1> text1 </h1>
    <h1> text2 </h1>
</div>

相关问题