使用动画 jquery 更改文本

Text changing with animation jquery

本文关键字:文本 jquery 动画      更新时间:2023-09-26

我有一些有效的代码,但有时它只是"跳"到其他文本而不尊重间隔。

该代码基本上按间隔更改标头的文本。

var text = ["text1", "text2", "text3","text4","text5"];
var index = 0;
$("#description").fadeOut("slow");
setInterval(function(){
    $("#description").html(text[index]).fadeIn("slow");
    $("#description").delay(400).fadeOut("slow");
    index++;
    if (index == 5) {
        index = 0;
    };
}, 1800);

如果你们能帮助我完成这项工作,甚至改进它,我将非常感谢:)

小提琴:http://jsfiddle.net/erbfqqxb/

我认为问题

可能是当您的间隔赶上延迟和褪色所需的时间时引起的。 尝试在回调中运行每个动画,以便将其作为线性过程运行,以防止文本"跳转":

var text = ["text1", "text2", "text3","text4","text5"];
var index = 0;
var description = $("#description");
description.fadeOut("slow", changeText);
function changeText(){
    // run the initial animation
    description.html(text[index]).fadeIn("slow", function() {

       // run the second animation after the first one has finished - can remove the delay if you want to
       // the delay here is how long you want the text to be visible for before it starts to fade out
        description.delay(400).fadeOut("slow", function() {
            index++;
            //measure against array length instead of hard coded length
            if (index == text.length) {
                index = 0;
            };
            //set the delay before restarting animation sequence (only restart once the sequence has finished)
            setTimeout(changeText, 400);
        });
    });
}

更新的小提琴

只需尝试如下:

setInterval(function(){
    //first stop what you are doing and then fadeIn again
    $("#description").stop().html(text[index]).fadeIn("slow",function(){
        //set a callback to do all these things once fadeIn is completed
        index++;
        $("#description").delay(400).fadeOut("slow");
        if (index == 5) {
            index = 0;
        };
    });
},1800);

我认为问题出在delay. setInterval时间和延误time是相互矛盾的。所以上面的方法对我来说似乎更好。

演示

我认为这是由于该行而发生的

$("#description").fadeOut("slow");

评论该行它将正常工作。

这是工作代码,它通过使用

index == text.length
 $(function() {
        var text = ["text1", "text2", "text3","text4","text5"];
        var index = 0;
        $("#description").fadeOut();
        setInterval(function(){
            $("#description").html(text[index]).fadeIn("slow");
            $("#description").delay(400).fadeOut("slow");
            index++;
            if (index == text.length) {
                index = 0;
            };
        },1800);
        });
    <pre>Use call back function and remove delay</pre>

吉斯菲德尔:http://jsfiddle.net/rajen_ranjith/erbfqqxb/3/。