Jquery / Javascript在滚动后找到第一个可见元素 [英] Jquery / Javascript find first visible element after scroll

查看:110
本文介绍了Jquery / Javascript在滚动后找到第一个可见元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下:

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

但实际上有很多很多的class ='item'。

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

基本上,当用户滚动这个很长的项目列表时,我想要更改当前顶部可见项目的样式(如Google阅读器!)。在jquery或普通的javascript中寻找解决方案,但似乎无法找到一个。有什么想法?

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 looked around for solution in jquery or plain javascript but can't seem to find one. Anyone have any ideas?

谢谢

标记

推荐答案

如果你的元素高度不同,你可以在滚动时迭代它们:

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
        }
    });
});

如果这太慢,你可以缓存$('。item')。offset()进入一个数组,而不是每次都调用offset()。

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

这篇关于Jquery / Javascript在滚动后找到第一个可见元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆