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

求助:Uncaught TypeError无法读取undefined的clientX属性

问题分析与解决

报错信息翻译

未捕获的类型错误:无法读取未定义的属性(读取'clientX')

问题原因

你直接调用movebackground()时没有传入事件对象,函数内的event参数是undefined,因此无法读取clientX属性。要实现鼠标移动时触发图形位移,必须将函数绑定到mousemove事件上,而非直接调用。

修改后的代码

const scaleFactor = 1 / 20;

function movebackground(event) {
    const shapes = document.querySelectorAll(".shape")

    const x = event.clientX * scaleFactor;
    const y = event.clientY * scaleFactor;

    for (let i = 0; i < shapes.length; ++i) {
        const isOdd= i % 2 !== 0;
        const boolInt = isOdd ? -1: 1;

        shapes[i].style.transform = `translate(${x * boolInt}px, ${y * boolInt}px)`
    }

    console.log(shapes)
}

// 将函数绑定到鼠标移动事件,浏览器会自动传入event对象
document.addEventListener('mousemove', movebackground);

补充说明

  • 直接调用函数时没有事件上下文,event为undefined,这是报错的核心原因。
  • 通过addEventListener绑定mousemove事件后,每次鼠标移动浏览器都会自动传递事件对象,函数就能正常获取clientX、clientY来计算位移了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 14:15:26