【问题标题】:How to show/hide divs with a delay in JQuery如何在 JQuery 中延迟显示/隐藏 div
【发布时间】:2013-04-15 19:43:57
【问题描述】:

我有一些代码尝试在延迟后一个接一个地显示和隐藏 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 在延迟后显示和隐藏?

【问题讨论】:

  • delay(1800).$ 是无效的语法。删除该位置的delay(1800). 部分。
  • 但是,即使我删除了它,它仍然无法正常工作,这个想法是每个盒子都应该是另一个隐藏
  • 对,这并不是一个解决方案,它只是为了修复直接的语法错误,这将导致您的代码根本无法工作,而不管它包含的逻辑错误如何。

标签: jquery html delay show-hide


【解决方案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 类。

【讨论】:

    【解决方案2】:

    用户 Kevin B 在 cmets 中提出以下建议。这照顾了我最初的答案所迎合的厄运的冗长性质/金字塔。

    $('#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();
    });
    

    【讨论】:

    • 使用 promise 对象可以使这看起来更简洁(没有厄运金字塔):jsfiddle.net/uXNjK/1
    • 凯文,太好了。非常感谢你给我看这个。我将在我的回答中包含您的建议。
    • 是否有可能整个循环,在 jquery 中是否有 goto 函数或某种 while 1=1 ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多