var box = document.querySelector('.box') var box1 = document.querySelector('.box1') box.onmousedown = function (e) { var e = e || window.event var e = event.offsetX var d = event.offsetY console.log(e) console.log(d) } box1.onmousemove = function (e) { var e = e || window.event var x =event.offsetX var y =event.offsetY console.log(x) console.log(y) box.style.left = x + 'px' box.style.top = y + 'px' } box1.onmouseup = function () { console.log('我要取消了移动事件') box1.onmousemove = null } 这段代码的错误
时间: 2023-12-29 17:05:21 浏览: 36
这段代码的错误在于以下几点:
1. 在 box.onmousedown 事件处理函数中,将 event 对象的 offsetX 属性赋值给了变量 e,导致后面的代码中 e 的值被覆盖,无法得到正确的鼠标点击位置。
2. 在 box1.onmousemove 事件处理函数中,获取鼠标移动位置时,将 event 对象的 offsetX 和 offsetY 属性分别赋值给了变量 x 和 y,但是变量 x 和 y 在后面的代码中没有被使用,导致无法实现 box 的移动。
3. 在 box1.onmouseup 事件处理函数中,尝试取消 box1.onmousemove 事件处理函数,但是这样是无法生效的,因为 box1.onmousemove 赋值为 null 并不会取消事件处理函数。
正确的代码应该是:
```javascript
var box = document.querySelector('.box');
var box1 = document.querySelector('.box1');
var offsetX, offsetY;
box.onmousedown = function (e) {
var e = e || window.event;
offsetX = e.offsetX;
offsetY = e.offsetY;
console.log(offsetX);
console.log(offsetY);
}
box1.onmousemove = function (e) {
var e = e || window.event;
var x = e.clientX - offsetX;
var y = e.clientY - offsetY;
console.log(x);
console.log(y);
box.style.left = x + 'px';
box.style.top = y + 'px';
}
box1.onmouseup = function () {
console.log('我要取消了移动事件');
box1.onmousemove = null;
}
```
在上述代码中,我们将鼠标点击位置的 offsetX 和 offsetY 值保存在变量中,在 box1.onmousemove 事件处理函数中,根据鼠标移动的位置计算出 box 的新位置,并将其赋值给 box 的 style.left 和 style.top 属性,实现了盒子的移动。在 box1.onmouseup 事件处理函数中,我们将 box1.onmousemove 赋值为 null,实现了取消 box1.onmousemove 事件处理函数的效果。