如何在JQuery中延迟显示/隐藏div

时间:2013-04-15 19:43:58

标签: jquery html delay show-hide

我有一些代码试图在延迟之后一个接一个地显示和隐藏div。

$('#box1').delay(1800).hide('slow');
delay(1800).$('#box2').delay(1800).show('slow');
delay(1800).$('#box2').delay(1800).hide('slow');
delay(1800).$('#box3').delay(1800).show('slow');
delay(1800).$('#box3').delay(1800).hide('slow');
delay(1800).$('#box4').delay(1800).show('slow');
delay(1800).$('#box4').delay(1800).hide('slow');
delay(1800).$('#box1').delay(1800).show('slow');

div没有显示和隐藏。如何在延迟后显示和隐藏div?

2 个答案:

答案 0 :(得分:1)

或许更符合这一点的事情会更好:

// Go over each .box in the collection
$(".box").each(function ( i ) {
    $(this)
        // Show after index * 1800 (0 * 1800, 1 * 1800, 2 * 1800, etc)
        .delay( i * 1800 ).show("slow")
        // Hide after same calculation
        .delay( i * 1800 ).hide("slow");
});

只需为每个框提供.box类。

答案 1 :(得分:0)

用户 Kevin B 在评论中提出以下建议。这照顾了我的原始答案照顾的厄运的冗长的性质/金字塔。

$('#box1').delay(1800).hide('slow').promise().then(function(){
    return $('#box2').delay(1800).show('slow').promise();
}).then(function(){
    return $('#box2').delay(1800).hide('slow').promise();
}).then(function(){
    return $('#box3').delay(1800).show('slow').promise();
}).then(function(){
    return $('#box3').delay(1800).hide('slow').promise();
}).then(function(){
    return $('#box4').delay(1800).show('slow').promise();
}).then(function(){
    return $('#box4').delay(1800).hide('slow').promise();
}).then(function(){
    return $('#box1').delay(1800).show('slow').promise();
});