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

Angular中使用fromEvent获取scrollTop等属性返回undefined问题排查

问题分析与解决:scrollTop返回undefined的原因

核心问题

你代码里的问题在于:

  • 绑定scroll事件到document后,事件对象的target是document本身(文档对象),而非DOM元素节点,document没有scrollTop属性,所以强制转换为Element后访问该属性会返回undefined。
  • scrollTop、scrollHeight、clientHeight这些属性属于DOM元素,具体来说是文档的根元素(<html>对应document.documentElement)或<body>元素(document.body),不同浏览器在标准/怪异模式下会使用不同的元素存储滚动数据。

修正代码方案

方案1:直接从正确的DOM元素获取滚动属性

ngOnInit(): void {
  const obs$ = fromEvent(document, 'scroll')
    .pipe(
      map(() => {
        // 兼容不同浏览器的滚动属性获取方式
        const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
        const clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
        
        console.log(scrollTop, scrollHeight, clientHeight);
        return { scrollTop, scrollHeight, clientHeight };
      })
    )
    .subscribe();
}

方案2:绑定事件到window(更推荐的滚动事件绑定方式)

滚动事件通常绑定到window对象更符合习惯,同时可以通过window.pageYOffset直接获取滚动位置:

ngOnInit(): void {
  const obs$ = fromEvent(window, 'scroll')
    .pipe(
      map(() => {
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
        const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
        const clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
        
        console.log(scrollTop, scrollHeight, clientHeight);
        return { scrollTop, scrollHeight, clientHeight };
      })
    )
    .subscribe();
}

额外说明

  • window.pageYOffset是更标准的滚动位置获取方式,兼容现代浏览器,老浏览器可以用document.documentElement.scrollTop或document.body.scrollTop兜底。
  • 若你是监听某个具体DOM元素的滚动(而非整个页面),则需要将事件绑定到该元素,此时事件的target就是该元素,可以直接访问其scrollTop等属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 22:27:20