【问题标题】:use hide/show in jquery each在 jquery 中分别使用隐藏/显示
【发布时间】:2012-04-24 03:21:18
【问题描述】:

此代码不起作用,我该如何解决?

我把所有的东西都隐藏了..之后,我在延迟 7 秒内一一显示..

但一切都显示出来了,我不明白为什么

$(function()    {
    texts = $('.text-block');
    slide = $('#slideshow');


    // hide everything
    texts.each(function()   {
       $(this).hide(); 
    });

    // show it once by once
    jQuery.each(texts, function()   {
       $(this).show(300);
       $(this).delay(7000);
       $(this).hide(300);
    });
});

【问题讨论】:

    标签: jquery delay show each slide


    【解决方案1】:

    因为它从同一点延迟,如果你把延迟放在正确的地方。

    $(function()    {
        texts = $('.text-block');
        slide = $('#slideshow');
    
    
        // hide everything
        texts.hide(); 
    
        // show it once by once
        texts.each( function(index)   {
           $(this).delay(7000 * index).show(300);
        });
    });
    

    您想在显示后再次隐藏它吗?我删除了它,因为它只会显示然后隐藏。

    缩短版:

    $(function() {
        $('.text-block').each(function(index){
            $(this).hide().delay(7000 * index).show(300);
        });
    });
    

    【讨论】:

    • 索引从 0 开始,可能你需要 (index+1) 延迟,texts.hide() 应该隐藏所有内容而不是 .each
    • 正确,取决于您是否想将第一个延迟 7 秒。
    • mm true.. 好回答 +1 来自我。
    【解决方案2】:

    首先,您不需要使用 .each,

    texts = $('.text-block');
    texts.hide(); // hides all matched elements
    

    就一一显示而言,延迟不会停止整个 js 线程的执行,这会阻塞且不好,并使您的应用程序看起来非常无响应。要一一显示它们,您会必须换个方式写

    也许是一个递归函数,你在延迟之后传递下一个元素,使用一个承诺来知道动画和延迟何时完成?

    像这样:

    http://jsfiddle.net/SbYTL/1/

    function ShowItems(items, delay) {
        $(items[0]).fadeIn(300)
            .delay(delay)
            .fadeOut(300)
            .promise()
            .done(function() {
                items.splice(0, 1);
                if (items.length > 0)
                {
                    ShowItems(items, delay);    
                }            
        });       
    }
    
    var items = $(".text-block").hide();  
    ShowItems(items, 7000);
    

    【讨论】:

    • 更新了 jsfiddle 示例以完全匹配您的问题,并附上示例用法。
    【解决方案3】:

    请改用.throttle 结帐。

    【讨论】:

    • 不错的主意,不过似乎很难与 foreach 一起使用。
    【解决方案4】:
    $(function() {
        $('.text-block').hide().each(function(item, index) {
             $(item).delay(7000*index).show(300, function() {
                 $(this).delay(7000).hide(300);
             });
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-20
      • 2011-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多