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

React中如何监听滚动事件并判断overflow:scroll的div是否横向滚到最右

实现方案

1. 核心属性说明

判断横向滚动位置需要用到DOM元素的三个只读属性:

  • scrollLeft:元素左侧已经滚动隐藏的水平像素值
  • clientWidth:元素可视区域的宽度(不含滚动条、边框、外边距)
  • scrollWidth:元素整个内容的总宽度,包括溢出滚动隐藏的部分

横向滚动示意图

2. 滚动事件绑定方式

在React中推荐直接通过JSX的onScroll属性绑定监听事件,配合useRef获取滚动元素的DOM实例,无需手动解绑事件,性能更优。

3. 滚动到最右侧的判断逻辑

当元素滚动到最右侧时,已滚动的距离加上可视宽度等于内容总宽度,考虑到小数像素、屏幕缩放带来的误差,可以预留1px的容错阈值:

元素是否滚到最右侧 = scrollLeft + clientWidth >= scrollWidth - 1

4. 完整代码示例

import { useRef, useState } from 'react';

function ScrollDemo() {
  // 存储是否滚动到最右侧的状态
  const [isScrollEnd, setIsScrollEnd] = useState(false);
  // 绑定滚动元素的ref
  const scrollContainerRef = useRef(null);

  const handleScroll = () => {
    const container = scrollContainerRef.current;
    if (!container) return;

    const { scrollLeft, clientWidth, scrollWidth } = container;
    // 计算是否滚动到最右侧,预留1px容错
    const isRightEnd = scrollLeft + clientWidth >= scrollWidth - 1;
    setIsScrollEnd(isRightEnd);
  };

  return (
    <div>
      <div style={{ marginBottom: 8 }}>
        {isScrollEnd ? '已经滚动到最右侧' : '未滚动到最右侧'}
      </div>
      {/* 绑定ref和滚动事件 */}
      <div
        ref={scrollContainerRef}
        onScroll={handleScroll}
        style={{
          width: '300px',
          overflowX: 'scroll',
          border: '1px solid #eee'
        }}
      >
        <div style={{ width: '800px', height: '100px', background: '#f5f5f5' }}>
          超长横向滚动内容
        </div>
      </div>
    </div>
  );
}

export default ScrollDemo;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 09:36:03