<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style type="text/css">
#d01{
100px;
height: 100px;
background-color: red;
position: absolute;
}
#d02{
100px;
height: 100px;
background-color: darkgreen;
position: absolute;
right: 220px;
top: 220px;
}
</style>
<body>
<div id="d01">
</div>
<div id="d02">
</div>
</body>
<script type="text/javascript">
/*拖拽d01元素
*-拖拽的流程:
* 1.当鼠标按下,开始拖拽 onmousedown
* 2.跟随鼠标移动 onmousemove
* 3.鼠标松开,元素固定在当前点 onmouseup
*/
var d01=document.getElementById("d01");
// 1.当鼠标按下
d01.onmousedown=function(){
// alert("鼠标按下,开始拖拽");
//设置鼠标点哪就是那的偏移量
//event.clientX-元素.offsetLeft
var ol=event.clientX-d01.offsetLeft;
var ot=event.clientY-d01.offsetTop;
// 2.跟随鼠标移动
document.onmousemove=function(event){
//改css移动d01
d01.style.left=event.clientX-ol+"px"; // -ol 完成偏移量
d01.style.top=event.clientY-ot+"px";
}
// 3.鼠标松开,元素固定在当前点
document.onmouseup=function(){ //document下的事件而不是d01,不然时间在另一块上消失
//就是取消onmousemove事件
document.onmousemove=null;
document.onmouseup=null; //一次性的事件,防止按下松开空白还存在这个事件
//alert("松开了");
}
/*
* 浏览器默认会有拖拽内容去搜索它,会出现写的拖拽不希望实现这时候要取消浏览器默认拖拽
*/
return false;
}
</script>
</html>