Jquery / Javascript find first visible element after scroll

后端 未结 3 1817
余生分开走
余生分开走 2020-12-06 10:54

I have code like below:

blah blah
blah blah 2&
3条回答
  •  一整个雨季
    2020-12-06 11:25

    If your elements aren't the same height, you can iterate over them on scroll:

    $(document).scroll(function() {
        var cutoff = $(window).scrollTop();
        $('.item').removeClass('top').each(function() {
            if ($(this).offset().top > cutoff) {
                $(this).addClass('top');
                return false; // stops the iteration after the first one on screen
            }
        });
    });
    

    If this is too slow, you can cache the $('.item').offset() into an array, rather than calling offset() each time.

提交回复
热议问题