分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > IT知识

jquery监听滚动事件获取scrollTop

发布时间:2023-09-06 02:15责任编辑:胡小海关键词:暂无标签
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

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved