首页 > Web开发 > 详细

jquery监听滚动事件获取scrollTop

时间:2018-09-16 17:09:46      阅读:144      评论:0      收藏:0      [点我收藏+]
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

原文:https://www.cnblogs.com/bber/p/9656540.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!