判断滚动条到达底部

72 阅读1分钟

判断标准:可视区域高度(容器) + 滚动条的距离顶部高度 >=  内容的整体高度

style

#scroll-view {
width: 600px;
height: 800px;
border: 1px solid blue;
overflow-y: auto;
}

#scroll-content {
height: 1200px;
}

html

<div id="scroll-view">
  <div id="scroll-content"></div>
</div>

js

document.querySelector("#scroll-view").addEventListener("scroll", (e) => {
  // scrollTop-滚动条距离顶部高度;clientHeight-可视区域高度
  const { scrollTop, clientHeight } = e.target;
  // 内容高度
  const contentHeight =
    document.querySelector("#scroll-content").scrollHeight;

  if (scrollTop + clientHeight >= contentHeight) {
    console.log("到达底部");
  }
});