滚动后显示元素,一个接一个

时间:2018-09-22 14:36:47

标签: jquery

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

<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.1s到几秒钟不等... settimeout对我也不起作用。

图片很少的示例:

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

如何在这个each()函数中包含适当的延迟? 感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

这是我发现的:

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 opacity VS jQuery function hide())< /p>

相关问题