Trigger an event each time an item scrolls into viewport

主宰稳场 提交于 2019-12-08 06:54:54

问题


I have some items on a page. When they scroll into view, I add animation classes to them, like this:

 $(window).scroll(function() {

    var topOfWindow = $(window).scrollTop(),
        bottomOfWindow = topOfWindow + $(window).height();

    $('.buckle').each(function(){
        var imagePos = $(this).offset().top;

        if (imagePos < topOfWindow+400) {
                $(this).addClass('animate');
        }


    });

   });

Here's a stripped-down JSFiddle demo

This triggers the animation to occur one time per page load: when the image is 400px from the top of the viewport, the class gets added, the animation rolls, then the image remains static.

But now they are meant to animate once each time they scroll into the viewport, whether the user is scrolling upwards or downwards. In the case of the demo, the "Buckle" element would lose the class .animate after scrolling out of view, and have it re-applied when scrolling back in to view.

What would be the most efficient approach for triggering this with JQuery?


回答1:


I'm not sure if I entirely understood you, but I think its not a very good idea to trigger the animation 400px from the top. What if the window/viewport's height is even less than 400px, the animation would be initiated before it was scrolled into view. I think it should be determined via the windows bottom.

$(window).scroll(function () {
    var topOfWindow = $(window).scrollTop(),
        bottomOfWindow = topOfWindow + $(window).height();

    $('.buckle').each(function () {
        var imagePos = $(this).offset().top;

        if(imagePos <= bottomOfWindow && imagePos >= topOfWindow){
            $(this).addClass('animate');
        }else{
            $(this).removeClass('animate');
        }
    });
});

Here's the demo: http://jsfiddle.net/2LPmr/1/

Cheers!



来源:https://stackoverflow.com/questions/22738674/trigger-an-event-each-time-an-item-scrolls-into-viewport

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!