1. 程式人生 > >jquery監聽滾動事件獲取scrollTop

jquery監聽滾動事件獲取scrollTop

測試 element UNC data- document font ole span 谷歌

css:
.anchor_reached { color: #0073eb; }
jquery:
$(window).scroll(function(event){
  $(".anchor_directory").siblings().each(function(){
    var this_top = $(this).attr("data-top");
    if(($(‘body‘).scrollTop()) >= this_top){
      $(this).addClass("anchor_reached").siblings().removeClass("anchor_reached");
    }
  })
})

/*************2018.9.16更新***************/

今天測試的時候發現有bug,scrollTop獲取到居然總是為0,我以前用了個假瀏覽器??

正題,無論火狐還是谷歌,console的結果都是0,chrome對document.documentElement.scrollHeight&document.documentElement.scrollTop是不能識別的,而firefox和IE11不能識別document.body.scrollHeight&document.body.scrollTop,所以要考慮的網頁的兼容性,建議兩種獲取方法都要寫在代碼裏。

修正後的代碼如下:
//監聽屏幕滾動條
$(window).scroll(function(event){
var oTop = document.body.scrollTop==0?document.documentElement.scrollTop:document.body.scrollTop;
//console.log(oTop)
$(".anchor_directory").siblings().each(function(){
var this_top = $(this).attr("data-top");
//console.log($(‘body‘).scrollTop()) //---0
if((oTop + 140) >= this_top){

$(this).addClass("anchor_reached").siblings().removeClass("anchor_reached");
}
})
});

jquery監聽滾動事件獲取scrollTop