Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript e、 clientX在控制台中是未定义的错误,但仍然有效_Javascript - Fatal编程技术网

Javascript e、 clientX在控制台中是未定义的错误,但仍然有效

Javascript e、 clientX在控制台中是未定义的错误,但仍然有效,javascript,Javascript,出于某种原因,控制台一直在说uncaughttypeerror:无法读取未定义的属性'clientX' 在moveCircle script.js:5中,但代码仍然可以在浏览器中运行。你能解释一下这个错误是如何出现在控制台上的吗 1 const CIRCLE = document.querySelector(".circle"); 2 const BODY = document.body; 3 4 function moveCircle(e) { 5 CIRCLE.style

出于某种原因,控制台一直在说uncaughttypeerror:无法读取未定义的属性'clientX' 在moveCircle script.js:5中,但代码仍然可以在浏览器中运行。你能解释一下这个错误是如何出现在控制台上的吗

1  const CIRCLE = document.querySelector(".circle");
2  const BODY = document.body;
3  
4  function moveCircle(e) {
5      CIRCLE.style.left = e.clientX + "px";
6      CIRCLE.style.top = e.clientY + "px";
7  }
8  
9  BODY.addEventListener("mousemove", moveCircle, false);
10 setInterval(moveCircle, 1);
setInterval调用的函数moveCircle没有事件对象

由事件mousemove触发的函数moveCircle将起作用


为什么要按setInterval调用moveCircle?

对于这类事情,请使用window requestAnimationFrame rAF,因为rAF或setTimeout无法直接访问事件,所以最好的选择是在某处记录事件并从那里使用它,或者存储最后的坐标并对其进行操作。像这样的可能


当你注释掉setInterval行时,错误应该消失。因为moveCircle中的e变量没有定义哦,是的,我想setInterval没有意义。谢谢。我忘记了requestAnimationFrame存在。
var circle = document.querySelector(".circle");
var pos = [0,0];
document.getElementById("container").addEventListener("mousemove",updatePos,false);
window.requestAnimationFrame(move);


function updatePos(e){
    pos[0] = e.clientX || 0;
  pos[1] = e.clientY || 0
}
function move(){
    var diffX = pos[0] - circle.offsetLeft;
  var diffY = pos[1] - circle.offsetTop;
  if(diffX) {
    circle.style.left = circle.offsetLeft+Math.max(-5,Math.min(diffX/10,5))+"px";
  }
  if(diffY) {
    circle.style.top = circle.offsetTop+Math.max(-5,Math.min(diffY/10,5))+"px";
  }
  window.requestAnimationFrame(move);
}