前言:年初换工作,换住处弄了好长一段时间,终于全部搞定了,好久没写博客了,今天小更新一下,以示存在 ~.~
话不多说,上代码
- html
<html><div class='div'></div></html>
- css
*{
margin: 0;
padding: 0;
}
.div{
position: relative;
left: 100px;
top: 100px;
background-color: blue;
width: 150px;
height: 150px;
cursor: pointer;
}
- javascript
var div = document.querySelector('.div');
var mouseX = 0;
var mouseY = 0;
function move(e){
var box = div.getBoundingClientRect();
var boxLeft = box.left;
var boxTop = box.top;
var temMouseX = e.clientX;
var temMouseY = e.clientY;
var moveX = temMouseX - mouseX;
var moveY = temMouseY - mouseY;
div.style.left = boxLeft + moveX + 'px';
div.style.top = boxTop + moveY+'px';
mouseX = e.clientX;
mouseY = e.clientY;
}
div.addEventListener('mousedown', function(e){
div.style.position = 'absolute';
mouseX = e.clientX;
mouseY = e.clientY;
document.addEventListener('mousemove', move);
})
document.addEventListener('mouseup', function(e){
document.removeEventListener('mousemove', move);
div.style.position = 'relative';
})
效果如下:
有几点值得注意的地方:
- 事件注册的时候,只有 mousedown事件是在 div上注册,其他事件是在 document上注册,这样是为了防止移动过快,鼠标移出 div而导致的 bug
- mouseX和 mouseY为缓存鼠标的坐标,在 move方法最后需要实时设置鼠标的坐标
- 移动前将 div的 position设置为 absolute能在移动过程中有效的减少回流