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

使用Locomotive JS设置cursor Img opacity为1遇TypeError问题求助

问题分析与解决方案

错误原因

出现TypeError: Cannot read properties of undefined (reading 'style')是因为你尝试操作的.cursor-img元素在代码执行时还未被DOM渲染出来:

  • 开启浏览器审查模式时,页面加载速度变慢,DOM有足够时间完成渲染,代码能正常找到元素;
  • Locomotive JS的初始化逻辑(比如平滑滚动、DOM重构)会改变页面渲染时序,导致元素加载延迟,退出审查模式后页面加载快,代码执行时元素还不存在,触发错误。

解决方法

  1. 确保DOM完全加载后执行代码
    把操作cursor的代码包裹在DOMContentLoaded事件中,确保DOM渲染完成后再执行:

    document.addEventListener('DOMContentLoaded', () => {
      const cursorImg = document.querySelector('.cursor-img');
      cursorImg.style.opacity = '1';
    });
    
  2. 在Locomotive初始化完成后执行代码
    利用Locomotive Scroll的init事件,等它完成初始化、DOM稳定后再操作元素:

    const scroll = new LocomotiveScroll({
      el: document.querySelector('[data-scroll-container]'),
      smooth: true
    });
    
    // 等Locomotive初始化完成后执行cursor逻辑
    scroll.on('init', () => {
      const cursorImg = document.querySelector('.cursor-img');
      cursorImg.style.opacity = '1';
    });
    
  3. 添加元素存在性检查(兜底方案)
    避免因元素找不到直接报错,添加判断:

    const cursorImg = document.querySelector('.cursor-img');
    if (cursorImg) {
      cursorImg.style.opacity = '1';
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 22:48:14