选择接触视口顶部边缘的元素的有效方法
当页面滚动时,什么是计算有效的方法来选择接触浏览器窗口视口顶部边缘的元素?
请参阅附图。选择绿色元素是因为它们接触顶部边缘。
更新
我将如何使用它的一个示例是淡入淡出正在消失的元素-屏幕。页面上可能有数百个。想象一下像 Pinterest 这样的页面。以滚动事件的速率计算数百个偏移量和滚动顶部,即使受到限制仍然感觉效率很低。
What would be computationally-efficient ways to select elements touching the top edge of browser window viewport as the page is scrolled?
See attached image. Green elements are selected because they are touching the top edge.
UPDATE
An example of how I'll use this is to fade elements that are going off-screen. There may be hundreds of them on the page. Imagine a page like Pinterest. Computing offset and scrollTop for hundreds of them at the rate of scroll event, even if throttled still feels really inefficient.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这就是我想出来的。我认为可以通过缓存scrollTop 值来改进它,但这非常好。我已经包含了用于缓存盒顶的框架,但没有包含实现代码。我也只实现了向下滚动来隐藏 div。我已经在向上滚动中重新显示它们作为您的练习。
当窗口滚动时,我们得到最后一个隐藏的 div。我们知道这个 div 之前的所有内容都已经隐藏了。然后使用“当下一个元素离开屏幕时”将其隐藏。一旦 div 没有离开屏幕,我们就会中止。从而节省了迭代整个列表的时间。
http://jsfiddle.net/kkv3h/2/
This is what I came up with. I think that it could be improved upon by caching the scrollTop values, but this is pretty good. I have included the framework for caching the boxtops, but not the implementation code. I have also only implemented scrolling down to hide divs. I have left reshowing them on upscroll as an exercise for you.
When the window is scrolled we get the last hidden div. We know that everything before this div is already hidden. Then use a 'while next element is off the screen' hide it. As soon as a div isn't off the screen we abort. Thus saving time from iterating through the entire list.
http://jsfiddle.net/kkv3h/2/
我认为最好的方法是您可以通过某个类标记您想要确定命中测试的元素,例如“命中测试可见”或其他内容。然后,对于这些元素,在滚动事件上,您应该能够找到它们相对于文档的偏移量 - 请参阅 jQuery offset,然后根据滚动值,如果偏移量小于滚动值,并且偏移量+元素高度大于滚动偏移量,则该元素应该“触及”顶部边缘。
I'm thinking the best way would be that you could mark elements you want to determine hit testing with by some class, say "hit-test-visible" or something. Then, for those elements, on the scroll event, you should be able to find their offset compared to the document - see jQuery offset, and then based on the scroll value, if the offset is less than the scroll, and the offset + element height is greater than the scroll offset, then the element should be "touching" the top edge.