JavaScript动画开发求助:setInterval/clearInterval使用报错
问题分析与代码修正
错误点说明
- 参数传递错误:
setInterval调用moveImage时未传入点击坐标,导致x、y为undefined,后续计算centerX/centerY时出现NaN错误 - 条件判断语法错误:
(imgX, imgX == centerX)错误使用逗号运算符,实际仅判断imgX == centerX,逻辑写法不符合需求 - 初始位置未处理:若图片未设置内联
left/top样式,parseInt(img.style.left)会返回NaN,导致移动逻辑直接失效
修正后的代码
let timerId = null; window.addEventListener("DOMContentLoaded", function() { document.addEventListener("click", startAnimation); }); function startAnimation(e) { // 获取鼠标点击坐标 let clickX = e.clientX; let clickY = e.clientY; // 若已有运行中的定时器,先清除 if (timerId !== null) { clearInterval(timerId); } // 立即执行一次移动,避免首次启动的延迟感 moveImage(clickX, clickY); // 启动定时器,通过箭头函数传递点击坐标 timerId = setInterval(() => moveImage(clickX, clickY), 10); }; function moveImage(x, y) { const img = document.querySelector("img"); // 用offsetLeft/offsetTop获取图片当前位置,无需依赖内联样式,避免NaN问题 let imgX = img.offsetLeft; let imgY = img.offsetTop; // 计算图片居中到点击位置的目标坐标 const centerX = Math.round(x - (img.width / 2)); const centerY = Math.round(y - (img.height / 2)); // 判断是否到达目标位置,到达则停止定时器 if (imgX === centerX && imgY === centerY) { clearInterval(timerId); timerId = null; return; // 终止后续无效的移动逻辑 } // 向目标位置每次移动1像素 if (imgX < centerX) { imgX++; } else if (imgX > centerX) { imgX--; } if (imgY < centerY) { imgY++; } else if (imgY > centerY) { imgY--; } // 更新图片的实际位置 img.style.left = imgX + "px"; img.style.top = imgY + "px"; };
关键修改说明
- 定时器参数传递:用箭头函数包裹
moveImage调用,确保每次定时器触发时都能传递当前点击的坐标参数 - 位置判断修复:将错误的逗号运算符写法改为
imgX === centerX && imgY === centerY,准确判断图片是否到达目标位置,同时添加return终止后续逻辑 - 初始位置处理:改用
offsetLeft/offsetTop获取位置,无需依赖内联样式,彻底避免NaN引发的错误 - 逻辑顺序调整:将到达目标的判断放在移动逻辑之前,避免到达后仍执行一次无效移动
内容的提问来源于stack exchange,提问作者Jerry
相关产品推荐
相关产品推荐

