求助: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
相关产品推荐
相关产品推荐

