滚动时捕获第一个可见的div id(视口) [英] Capture first visible div id while scrolling (viewport)
问题描述
我有这个页面:
我想在我滚动的时候捕捉到我的div。
I want to capture on which div I am while I'm scrolling.
我知道如果我使用:
if( $(document).scrollTop() > $('#div1').position().top) {
console.log('Div1')
}
...它将捕获div1但不是为每个div使用此代码我想为所有div设置1个片段
...it will capture the div1 but instead of using this code for every div I want to set 1 snippet for all divs
类似于:
var a = // The div i am at
if( $(document).scrollTop() > $(a).position().top) {
console.log($(a).attr('id'))
}
我看起来像视口: http ://www.appelsiini.net/projects/viewport/3x2.html
我可以在没有插件的情况下实现这一目标,只需2 -3行?
Can I achieve that without a plugin, simply 2-3 lines?
推荐答案
这是一个很好的方法。您可能希望使用像素偏移优化'< ='以改善用户体验并在回调之外移动div选择器($ divs)以提高性能。看看我的小提琴: http://jsfiddle.net/brentmn/CmpEt/
Here's a nice way to do it. You may want to optimize the '<=' with a pixel offset to improve user experience and move the div selector ($divs) outside the callback to increase performance. Have a look at my fiddle: http://jsfiddle.net/brentmn/CmpEt/
$(window).scroll(function() {
var winTop = $(this).scrollTop();
var $divs = $('div');
var top = $.grep($divs, function(item) {
return $(item).position().top <= winTop;
});
});
这篇关于滚动时捕获第一个可见的div id(视口)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!