jquery監聽滾動事件獲取scrollTop


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");
}
})
});


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM