开发者

Jquery / Javascript find first visible element after scroll

I have code like below:

<div id="container">
<div class="item" id="1">blah blah</div>
<div class="item" id="2">blah blah 2</div>
</div>

But actually there are lots and lots of with class='item'.

Basically as the user scrolls this great long list of items I want to change the style of the current top visible one (like google reader!). Have 开发者_StackOverflowlooked around for solution in jquery or plain javascript but can't seem to find one. Anyone have any ideas?

Thanks

Mark


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.


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()


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜