首页
归档
笔记
树洞
搜索
友言

文章详情

Interesting People Record Interesting.

/ JavaScript / 文章详情

js 解决判断滚动条触底时由于scrollTop是小数造成的问题

Sonder
2022-09-15
876字
2分钟
浏览 (2.5k)

一开始根据常规的做法代码如下:

复制代码
  //判断滚动条触底的情况
   if (scrollTop + clientHeight  = scrollHeight) {
     // todo
     return;
   }

始终没法判断触底,调试得知手机浏览器下 scrollTop 是小数,而 clientHeight 和 scrollHeight 始终是整数这是 bug 出现的根本原因。

2ebe96c16ad83378538271839494a60.jpg

解决方法:加1解决法

复制代码
 //判断滚动条触底的情况
   if (scrollTop + clientHeight + 1 >= scrollHeight) {
     //todo
     return;
   }

== 遇到 scrollTop 的问题其实都可以多一层思考,是否需要 +1 来兼容浏览器,解决 bug 。至此,问题解决。

完整代码:

复制代码
   window.onscroll = function() {
       let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;//据顶部距离
       let windowHeight = document.documentElement.clientHeight || document.body.clientHeight;//可视高度
       let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;//滚动条总高度
       if (scrollTop + windowHeight + 1 >= scrollHeight) {
           //写后台加载数据的函数

           })
       }
   }
下一篇 / 盘点 Vue2 和 Vue3 的10种组件通信方式

🎯 相关文章

💡 推荐文章

🕵️‍♂️ 评论 (0)