拖拽

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>拖拽</title>
</head>
<body>
<div style="width: 200px; height: 200px; background-color: #eee; position: absolute;" id="div1"></div>
<script>
window.onload=function(){
var oDiv=document.getElementById('div1');
var divX=0;
var divY=0;
oDiv.onmousedown=function(ev){
var oEvent=ev||event;
divX=oEvent.clientX-oDiv.offsetLeft;
divY=oEvent.clientY-oDiv.offsetTop;
document.onmousemove=function(ev){ //给document加事件是防止事件加在div上时 鼠标划出div onmousemove不起作用
var oEvent=ev||event;
oDiv.style.top=oEvent.clientY-divY+'px';
oDiv.style.left=oEvent.clientX-divX+'px';
}
document.onmouseup=function(ev){
oDiv.onmouseup=null;
oDiv.onmousemove=null;
}
return false; //火狐低版本bug 及第二次划动时出问题
}
}
</script>
</body>
</html>

你可能感兴趣的:(拖拽)