setTimeout未添加延迟

setTimeout not adding a delay

本文关键字:延迟 添加 setTimeout      更新时间:2023-09-26

这是我的代码:

function transition(index){
    $("#right-panel").find("img").each(function(){
        if ($(this).index() === index){
            setTimeout(function(){
                $(this).fadeIn(750);
            }, 100000000);
        }else{
            $(this).fadeOut(750);
        }
    });
}

由于某种原因,函数中的setTimeout不会导致fadeIn延迟。我做错了什么?

setTimeout回调中的this与其外部不同。

var self = this;
setTimeout(function(){
    $(self).fadeIn(750);
}, 100000000);

尽管您可以只使用.delay()

$(this).delay(100000000).fadeIn(750)

总的来说,一个更好的方法似乎是使用.eq()来获取你想要的.fadeIn(),而使用.fadeOut()来获取其余的

function transition(index){
    var images = $("#right-panel").find("img");// get all the images
    var fadein = images.eq(index)
                       .delay(100000000)
                       .fadeIn(750); // fadeIn the one at "index"
    images.not(fadein).fadeOut(750); // fadeOut all the others
}

为什么需要setTimeout?

function transition(index){
    $("#right-panel").find("img").each(function(){
        if ($(this).index() === index){ // did you check this statement?
            $(this).delay(100000000).fadeIn(750);
        }else{
            $(this).fadeOut(750);
        }
    });
}