<!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(){
/* 拖拽Box1 元素:
拖拽的流程
1. 当鼠标在拖拽元素上按下的时候,开始
拖拽 onmousedown
2. 当鼠标移动的时候被拖拽的时候被拖拽元素跟随鼠标移动
onmousemove
3.当鼠标松开的时候,被拖拽元素固定在当前位置
onmouseup */
var box1=document.getElementById("box1");
box1.onmousedown=function(){
/* 为box1 绑定一个鼠标按下事件
当鼠标在被拖拽的元素按下的时候,开始拖拽onmousedown */
document.onmousemove=function(event){
event=event||window.event;
var left=event.clientX;;
var top=event.clientY;
//修改box1的位置
box1.style.left=left+"px";
box1.style.top=top+"px";
};
box1.onmouseup=function(){
document.onmousemove=null;
document.onmouseup=null;
};
};
};
</script>
</head>
<body>
<div id="box1"></div>
<div id="box2"></div>
</body>
</html>
运行结果: