Jquery / Javascript find first visible element after scroll

后端 未结 3 1742
余生分开走
余生分开走 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.

    0 讨论(0)
  • 2020-12-06 11:32

    You can create your own scroller using javascript.

    It's not very practical idea but you can try.

    And place the link to the image describing it better. It would be very usable.

    0 讨论(0)
  • 2020-12-06 11:36

    Here is one more idea, based on built-in javascipt functions.

    var range = document.caretRangeFromPoint(0,0); // screen coordinates of upper-left corner of a scolled area (in this case screen itself)
    var element = range.startContainer.parentNode; // this an upper onscreen element
    

    This bit of code is not a ready-to-use product — it's just an example, that works only in webkit browsers. If you want to use it, you should google for cross-browser equivalents of caretRangeFromPoint()

    0 讨论(0)
提交回复
热议问题