首页 > 解决方案 > 滚动后显示元素,一个接一个

问题描述

我有一些图像要在页面上显示,我希望它们在滚动时延迟。

<div>
<img src="A.jpg" class="hidden"> <img src="B.jpg" class="hidden">
...
<img src="C.jpg" class="hidden"> <img src="D.jpg" class="hidden">
</div>

滚动页面后,我需要元素(在同一行)一一出现。由于该功能基于元素位置,如果元素具有相同的垂直位置,它们会同时出现,这是我不想要的。如果我在同一行上有 3 个图像,我希望它们一个接一个地出现。

接下来,当页面再次滚动时,脚本再次检查是否有新元素,并以 500ms 的延迟逐个显示。

<script>
    /* every time the window is scrolled ... */
    $(window).scroll(function() {
        show();
    });
    function show (){
        /* Check the location of each element */
        $('.hidden').each(function(index) {
            var visibility = $(this).css('opacity')
            var size = ($(this).outerHeight());
            var object = $(this).offset().top + size;
            var bottom_of_window = $(window).scrollTop() + $(window).height();

            /* If the object is not visible yet, and it's position is now scrolled */
            if (visibility == 0) {
                if (bottom_of_window > object) {
                    $(this).animate({'opacity': '1'}, 500);
                }
            }
        });
    };
</script>

我试图添加延迟:

var time = 500;
/*...*/
$(this).delay(time).animate({'opacity': '1'}, 500);
time = time + 500;

但它同时延迟了 3 个图像(所有行),而不是每一个都在前一个之后。

我试过使用索引来做类似的事情,time = index*100但它不适用于快速/大滚动,索引增长太多,结果从 0.1 秒到几秒不等......它对我也不起作用与settimeout.

带有少量图像的示例:

http://jsfiddle.net/24M3n/1654/

如何在此 each() 函数中包含适当的延迟?谢谢你的帮助 !

标签: jquery

解决方案


这是我发现的:

var elementPosition,bottomWindow,lastPosition,delay=0;
    $('.hiddenelement').each(function () {
        elementTopPosition= $(this).offset().top;
        bottomWindow= $(window).scrollTop() + $(window).height();    
        // If the object is visible in the window
        if (bottomWindow > elementTopPosition ) {
            //if element is on the same line than the previous one, add a delay
            if(elementTopPosition == lastPosition){
                delay=delay+250;
            }
            else{
                //reset delay if it is a different line
                delay=0;
            }
            lastPosition=elementTopPosition ;
            //show element with the appropriate delay
            setTimeout(function(){
                $(this).show('slow');   
            },delay);
        };
    });

想法是一样的,我只是取了顶部元素位置而不是底部,延迟更短,并且对元素的操作有所改变(编辑 css opacityVS jQuery 函数hide()


推荐阅读