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

LocomotiveScroll报错:Cannot read properties of undefined (reading 'inView')求助

LocomotiveScroll 初始化报错排查:Cannot read properties of undefined (reading 'inView')

配置LocomotiveScroll时出现以下报错,导致给body添加scrolled类的功能失效,但滚动组件本身仍能运行。对比之前正常的旧版本未发现差异,无法定位问题,求解决方向。

报错信息

locomotive-scroll.js?m=1683112609:2609 Uncaught TypeError: Cannot read properties of undefined (reading 'inView')
    at locomotive-scroll.js?m=1683112609:2609:26
    at NodeList.forEach (<anonymous>)
    at _default.addElements (locomotive-scroll.js?m=1683112609:2570:13)
    at _default.init (locomotive-scroll.js?m=1683112609:2127:14)
    at Smooth.init (locomotive-scroll.js?m=1683112609:3098:21)
    at new Smooth (locomotive-scroll.js?m=1683112609:3083:12)
    at loco.js?m=1683388185:1:16

我的loco.js代码

const scroll = new LocomotiveScroll({
    el: document.querySelector('[data-scroll-container]'),
    smooth: true,
    // smoothMobile: true,
});

scroll.on('scroll', (position) => {
  if ((position.scroll.y) > 50) {
    document.querySelector('body').classList.add('scrolled');
  } else {
    document.querySelector('body').classList.remove('scrolled');
  }
});

排查及解决方向

  • 检查页面中data-scroll属性元素:这个报错大概率是页面里存在格式错误的data-scroll属性元素(比如只加了data-scroll但没赋值,或者属性值不符合组件要求)。遍历所有带该属性的元素,要么修正属性值格式,要么移除不需要监听滚动状态的元素上的data-scroll属性。
  • 确认滚动容器存在:初始化前先验证[data-scroll-container]元素是否存在,避免容器为null导致内部解析异常:
    const container = document.querySelector('[data-scroll-container]');
    if (container) {
      // 初始化LocomotiveScroll
    }
    
  • 锁定组件版本:虽然你认为版本无差异,但可能存在CDN缓存或隐性依赖更新问题,直接切换回之前正常运行的LocomotiveScroll版本测试。
  • 确保DOM完全加载后初始化:如果页面存在动态渲染元素,用DOMContentLoaded事件包裹初始化逻辑,避免组件解析未渲染完成的DOM:
    document.addEventListener('DOMContentLoaded', () => {
      const scroll = new LocomotiveScroll({
        el: document.querySelector('[data-scroll-container]'),
        smooth: true,
      });
    
      scroll.on('scroll', (position) => {
        // 简化写法:用toggle替代判断
        document.body.classList.toggle('scrolled', position.scroll.y > 50);
      });
    });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 00:13:12