2012-01-26 63 views
2

我有这个页面:捕捉第一个可见的DIV ID时滚动(视)

enter image description here

我想捕捉在其上的div我,而我滚动。

我知道如果我使用:

if($(document).scrollTop() > $('#div1').position().top) { 
console.log('Div1') 
    } 

...这将捕获DIV1但不是使用此代码为每一个DIV我想设置1段的所有div

喜欢的东西:

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行?

回答

5

这是一个很好的方法来做到这一点。您可能需要优化'< ='像素偏移量以改善用户体验,并将回调区外部的选择器($ divs)移至回调之外以提高性能。看看我的小提琴: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; 
    }); 
}); 
0

只是把它扔进一个循环。

var list = []; 
$("div").each(function(index) { 
    if($(document).scrollTop() > $(this).position().top) 
     list.push($(this)); 
}); 

alert(list); 

该列表将比每个div都在您的视口。

0

我建议使用jQuery插件Inview:

https://github.com/protonet/jquery.inview

保持良好的插件检测任何内容是观众目前,使您能够绑定功能的inview事件。因此,只要您的div在视图中,就可以启动您想要的所有相关功能,然后在它离开用户视图时再次启动。对你的需求会很好。

+0

谢谢虽然有数以千计的插件实现我想要的东西,因为说我不想使用任何类型的插件。正如Brent所回答的那样,一行2行代码就可以解决这个问题。 – jQuerybeast 2012-01-27 02:44:31

+0

对不起,我一定跳过了!布伦特的方法是前进的道路:) – 2012-01-27 10:06:33

0
$(window).scroll(function() { 

     $("#privacyContent div").each(function() { 
      var bottomOffset = ($(this).offset().top + $(this).height()); 
      console.log("Botom=",bottomOffset ,"Win= ", $(window).scrollTop()); 
      if (bottomOffset > $(window).scrollTop()) { 

       $("#menu a").removeClass("active"); 
       // console.log("Div is= ",$(this).attr('id')); 
       $("#menu a[href='#" + $(this).attr('id') + "']").addClass("active"); 
       $(".b").removeClass("fsActive"); 
       var div = $(this); 
       div.find(".b").addClass("fsActive"); 

       return false; 
      } 
     }); 

}); 

我不喜欢这样它工作正常但检测出所有的DIV ID

+0

它给我只有一个div ID,这是顶部浏览器...!当其他div达到顶部时,它不显示...你能帮我吗? – 2016-06-08 15:45:42

+0

我想要每个在屏幕上可见的div id。 – 2016-06-09 03:48:56