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

Next.js中window.scrollY始终为0的问题求助

解决Next.js中InfiniteScroll组件onScroll事件获取window.scrollY始终为0的问题

核心原因

你设置了scrollableTarget="scrollableDiv",说明当前的滚动容器是id为scrollableDiv的元素,而非全局window对象。滚动事件只发生在这个容器内部,window本身没有产生滚动行为,所以window.scrollY和window.scrollX自然始终为0。

解决方案

方法1:通过事件对象获取容器的滚动位置

修改你的onScroll函数,直接从事件目标元素中读取滚动值:

const onScroll = (e) => {
  // e.target就是scrollableDiv容器元素
  console.log('垂直滚动距离:', e.target.scrollTop);
  console.log('水平滚动距离:', e.target.scrollLeft);
}

方法2:通过元素引用获取滚动位置

用useRef获取scrollableDiv的引用,随时读取它的滚动状态:

import { useRef } from 'react';

// 创建元素引用
const scrollableDivRef = useRef(null);

const onScroll = () => {
  if (scrollableDivRef.current) {
    console.log('垂直滚动距离:', scrollableDivRef.current.scrollTop);
    console.log('水平滚动距离:', scrollableDivRef.current.scrollLeft);
  }
}

// 组件中绑定引用和事件
<Styled.PageContainer ref={scrollableDivRef} id="scrollableDiv" onScroll={onScroll}>
<InfiniteScroll
  dataLength={articles?.length || 0}
  next={() => {
    fetchMore({
      variables: {
        offset: articles?.length || 0,
      },
    });
  }}
  hasMore={articles?.length < articlesCount}
  loader={<></>}
  scrollableTarget="scrollableDiv"
  onScroll={onScroll}
>

特殊情况:如果需要监听window滚动

如果你本来就想监听全局window的滚动,需要去掉scrollableTarget配置,让InfiniteScroll默认绑定到window上。同时要确保页面的body和html没有设置overflow:hidden等会改变滚动容器的样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 03:17:14