使用 jQuery 查找滚动 div 顶部和底部的 DOM 元素
我有一个包含列表项的滚动 div。我在此滚动事件函数内部定义了
$("#scrollingDiv").scroll(function(e) {
});
此样板滚动事件,如何确定哪些元素位于当前可见区域的顶部和底部?
I have a scrolling div containing list items. I have this boilerplate scroll event defined
$("#scrollingDiv").scroll(function(e) {
});
Inside of this scroll event function, how can I figure out which elements are at the top and bottom of the currently visible area?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试计算列表项相对于滚动
的位置,然后扫描位置以查看哪些位置与
scrollTop
相匹配。代码>也许是这样的:
实时版本(请打开您的控制台): http://jsfiddle.net/ambigously/yHH7C/
您可能希望利用
if
的模糊性来获得一些可以合理工作的东西(1px 可见很难使元素成为顶部元素),但基本思想应该足够清晰。混合#scrollingDiv
的高度可以让您看到哪个位于底部。
如果您有很多列表项,那么线性搜索可能不是您想要的,但您应该能够轻松解决这个问题。
You could try computing the positions of the list items with respect to the scrolling
<div>
and then scan the positions to see which ones match up with thescrollTop
of the<div>
.Something like this perhaps:
Live version (open your console please): http://jsfiddle.net/ambiguous/yHH7C/
You'd probably want to play with the fuzziness of the
if
to get something that works sensibly (1px visible hardly makes an element the top one) but the basic idea should be clear enough. Mixing in the height of#scrollingDiv
will let you see which<li>
is at the bottom.If you have a lot of list items, then a linear search might not be what you want but you should be able to solve that without too much effort.