在 mousemove 事件侦听器函数体中设置左侧位置不起作用

Setting left position in the body of mousemove event listener function doesn't work

我希望我的 div 的位置左值之一等于我的 mousemove event.clientX。尽管我的代码中的 individual 项可以自行运行,但以下代码不起作用。为什么?

var shapeCanvas = document.getElementsByClassName("shape")[0];
shapeCanvas.style.left = '1px';  // works 

document.getElementsByClassName("body")[0]
.addEventListener("mousemove",function(e){
   shapeCanvas.style.left = e.clientX + "px"; // **doesn't work**
   console.log(e.clientX); // works also 
},false); 

您试图通过正文 class 而不是标签来识别正文元素。我改为将 eventListener 添加到 window,以获得更好的结果。这是您想要实现的目标吗?

var shapeCanvas = document.getElementsByClassName("shape")[0];
shapeCanvas.style.left = '1px';  // works 

window.addEventListener("mousemove",function(e){
   shapeCanvas.style.left = e.clientX + "px"; // **doesn't work**
   console.log(e.clientX); // works also 
},false); 
.shape{
  width:100px;
  height:100px;
  position:absolute;
  background:lightblue;
  }
<div class="shape">

</div>