我希望我的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);
答案 0 :(得分:1)
您试图通过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>