我希望我的 div 的左位置值之一等于我的 mousemove
event.clientX
。尽管我的代码中的各个项目可以自行工作,但以下代码不起作用。为什么?
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);
最佳答案
您试图通过 body 类而不是标签来识别 body 元素。我将 eventListener 添加到窗口中,以获得更好的结果。这是您想要实现的目标吗?
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>
关于javascript - 在 mousemove 事件监听器函数主体中设置左侧位置不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38201932/