步骤:
1.当鼠标在被拖拽元素上按下时,开始拖拽onmousedown
2.鼠标移动时被拖拽元素跟随鼠标移动onmousemove
3.鼠标松开时,被拖拽元素固定当前位置onmouseup
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
#box1{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
}
#box2{
width: 100px;
height: 100px;
background-color: yellow;
position: absolute;
left:200px;
top:200px;
}
</style>
<script type="text/javascript">
window.onload = function(){
var box1 = document.getElementById("box1");
// box1绑定鼠标按下事件
// 当鼠标在被拖拽元素上按下时,开始拖拽onmousedown
box1.onmousedown = function(event){
event = event||window.event;
var ol = event.clientX-box1.offsetLeft;
var ot = event.clientY-box1.offsetTop;
// 为document绑定onmousemove事件
document.onmousemove = function(event){
event = event || window.event;
// 鼠标移动时被拖拽元素跟随鼠标移动onmousemove
// 获取鼠标坐标
var left = event.clientX - ol;
var top = event.clientY - ot;
// 修改box1位置
box1.style.left = left+"px";
box1.style.top = top+"px";
};
// 为document绑定一个鼠标松开事件
document.onmouseup = function(){
// 鼠标松开时,被拖拽元素固定当前位置onmouseup
// 取消document中onmousemove事件
document.onmousemove = null;
document.onmouseup = null;
};
};
};
</script>
</head>
<body>
<div id="box1"></div>
<div id="box2"></div>
</body>
</html>