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

转载于:https://www.cnblogs.com/bber/p/9656540.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值