拖拽的流程:
1、当鼠标在被拖拽元素上按下时,开始拖拽 onmousedown
2、当鼠标移动时被拖拽元素跟随鼠标移动 onmousemove
3、当鼠标松开时,被拖拽元素固定在当前位置 onmouseup
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
#box1{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
}
#box2{
width: 100px;
height: 100px;
background-color: yellow;
position: absolute;
top:200px;
left: 200px;
}
</style>
</head>
<body>
<div id="box1"></div>
<div id="box2"></div>
</body>
</html>
<script>
window.onload=function(){
//获取box1
var box1=document.getElementById('box1');
//给box1绑定一个鼠标按下事件
box1.onmousedown=function(){
//给document绑定一个onmousemove事件
document.onmousemove=function(e){
e=event||window.event; //考虑兼容性
//获取鼠标坐标
var left=event.clientX;
var top=event.clientY;
//修改box1的位置
box1.style.left=left+'px';
box1.style.top=top+'px';
//为元素绑定一个鼠标松开事件
// box1.οnmοuseup=function(){ //问题 1??
//取消document的onmousemove事件
// document.οnmοusemοve=null;
document.onmouseup=function(){
document.onmousemove=null;
//取消document的onmouseup事件
document.onmouseup=null;
};
};
};
};
</script>
代码中问题1: 当box1经过box2时,松开鼠标时box1并不能定住 还继续随鼠标移动 并且鼠标移动到了box2上 如下图:
所以并不是给box1绑定onmouseup事件 而是给document绑定onmouseup事件
还有一个问题是:鼠标现在一直是在元素的左上角 为了更好的体验效果(鼠标可以点击元素的任意位置移动) 需要做以下步骤:
由上图可以得出:
div的偏移量 鼠标.clientX(绿线)- 元素.offsetleft(粉线)
div的偏移量 鼠标.clientY(绿线)- 元素.offsetTop(粉线)
box1.onmousedown=function(e){
e=event||window.event;
var ol=event.clientX-box1.offsetLeft;
var ot=event.clientY-box1.offsetTop;
document.onmousemove=function(e){
e=event||window.event;
//获取鼠标坐标
var left=event.clientX-ol;
var top=event.clientY-ot;
//修改box1的位置
box1.style.left=left+'px';
box1.style.top=top+'px';
}