You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何捕获div元素滚动到底部时的滚动位置?

捕获特定div滚动到底部时的滚动位置解决方案

核心判断逻辑

要判断div是否滚动到底部,关键对比三个元素属性:

  • scrollTop:元素已滚动的垂直距离
  • clientHeight:元素可视区域高度
  • scrollHeight:元素内容总高度(含不可见部分)

当 scrollTop + clientHeight >= scrollHeight(可加小误差范围)时,说明已滚动到底部,此时即可记录当前scrollTop值。


原生JavaScript实现示例

// 获取目标div
const targetDiv = document.getElementById('target-scroll-div');

// 滚动事件处理函数
function handleDivScroll() {
  const { scrollTop, clientHeight, scrollHeight } = this;
  // 加2px误差范围,避免浏览器渲染精度问题导致误判
  if (scrollTop + clientHeight >= scrollHeight - 2) {
    // 记录滚动到底部时的位置
    const bottomPosition = scrollTop;
    console.log('滚动到底部的位置:', bottomPosition);
    // 此处可添加业务逻辑,比如存储位置、触发加载等
  }
}

// 绑定滚动事件,passive: true优化性能
targetDiv.addEventListener('scroll', handleDivScroll, { passive: true });

关键注意事项

  • 确保目标div设置overflow: auto或overflow: scroll样式,否则不会触发scroll事件
  • 误差范围的必要性:部分浏览器渲染时,scrollHeight与scrollTop + clientHeight可能存在1-2px偏差,添加偏移量可避免误判
  • 若div内容为动态加载(如滚动加载更多),需在内容更新后重新校验,因为scrollHeight会随内容变化
  • 如需移除事件监听,可使用targetDiv.removeEventListener('scroll', handleDivScroll)

Vue3框架实现示例

<template>
  <div ref="scrollDiv" class="scroll-box" @scroll="handleScroll">
    <!-- 自定义内容区域 -->
  </div>
</template>

<script setup>
import { ref } from 'vue';
const scrollDiv = ref(null);

const handleScroll = () => {
  const el = scrollDiv.value;
  if (!el) return;
  const { scrollTop, clientHeight, scrollHeight } = el;
  if (scrollTop + clientHeight >= scrollHeight - 2) {
    console.log('滚动到底部的位置:', scrollTop);
  }
};
</script>

<style scoped>
.scroll-box {
  height: 500px; /* 设置固定高度 */
  overflow-y: auto;
}
</style>

内容的提问来源于stack exchange,提问作者MLElyakan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 14:55:20