JQuery delay before fadeOut

核能气质少年 提交于 2019-12-09 08:19:04

问题


I have written a jquery script that allows me to fade divs in and out, then repeat. The code works fine. However, when I try to add a delay (I want the div to stay up a few seconds before fading out), it does not work properly. I've tried adding the delay in several places inside the code and none seem to function properly. I am using Jquery version 1.9.1

Here is the script that I have written:

$(document).ready(function(){
   ShowPostDiv(0);
});

function ShowPostDiv(divIndex)
{
    $(".home_entry_txt").hide();

    if(divIndex >= $(".rotate_hide").length)
    {
        divIndex = 0;
    }
    var divPostHtml = $(".rotate_hide:eq("+divIndex+")").html();
    $(".home_entry_txt").html(divPostHtml); 
    $(".home_entry_txt").fadeIn(3000, function(){
             $(".home_entry_txt").fadeOut("slow");
        });
    divIndex++;
    setTimeout("ShowPostDiv("+divIndex+")", 4000);
}

回答1:


You can just write

$(".home_entry_txt").fadeIn(3000).delay(1000).fadeOut("slow");



回答2:


try this

$(document).ready(function(){
   ShowPostDiv(0);
});

function ShowPostDiv(divIndex)
{
    $(".home_entry_txt").hide();

    if(divIndex >= $(".rotate_hide").length)
    {
        divIndex = 0;
    }
    var divPostHtml = $(".rotate_hide:eq("+divIndex+")").html();
    $(".home_entry_txt").html(divPostHtml); 
    $(".home_entry_txt").fadeIn(3000, function(){
        setTimeout(function(){
            $(".home_entry_txt").fadeOut("slow");
        },4000);
    });
    divIndex++;
}



回答3:


Have you tried .delay()? something like:

$(".home_entry_txt").fadeIn().delay(200).queue(function(next) {
$(".home_entry_txt").fadeOut("slow");
});



回答4:


I think that the problem is that you have to pass a function as the first parameter, and you are passing a string. Try replacing your setTimeout() Line with this:

setTimeout(function(){
    ShowPostDiv(divIndex);
}, 4000);

Source: http://www.w3schools.com/jsref/met_win_settimeout.asp



来源:https://stackoverflow.com/questions/15686598/jquery-delay-before-fadeout

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!