js如何获取滚动条到底部

198 阅读1分钟

实现思路

关键是要获取 元素的 scrollTop, clientHeight, scrollHeight, 这三者分别代表

scrollTop: 视口顶部具体滚动条顶部的距离

clientHeight: 视口的高度;

scrollHeight: 滚动区域的总高度

到最底部时: scrollTop + clientHeight = scrollHeight

实现demo

  • html
 <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>JS Bin</title>
    </head>
    <body>
      <div id='all'>
        <div>xxx</div>
        <div>xxx</div>
        <div>xxx</div>
        <div>xxx</div>
        <div>xxx</div>
        <div>xxx</div>
      </div>
    </body>
</html>
  • js代码
    document.getElementById('all').addEventListener('scroll', (e) => {
          const {clientHeight, scrollTop, scrollHeight} = e.target
          // const {clientHeight, scrollTop, scrollHeight} = e.currentTarget
          if( clientHeight + scrollTop  = scrollHeight) {
              alert('已经到底部啦')
          }
    })
  • css代码
    #all {
      height: 70px;
      overflow: scroll
    }

注意点

在获取上述三个参数时,可以基于 e.target 或者 e.currentTarget 都可以获取

对于 e.target 是指触发事件的dom元素;

e.currentTarget 是指侦听器所在的dom元素