<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>拖拽练习</title>
<style>
#moveBox{
width: 100px;
height: 100px;
background-color: #bfa;
position: absolute;
}
#box1{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top: 100px;
}
</style>
</head>
<body>
<div id="moveBox">
</div>
<div id="box1">
</div>
</body>
<script>
var moveBox = document.getElementById("moveBox");
moveBox.onmousedown = function(event){
// 鼠标相对于元素的偏移量
var mouseX = event.offsetX;
var mouseY = event.offsetY;
window.onmousemove = function(event){
var x = event.pageX;
var y = event.pageY;
moveBox.style.left = x - mouseX + "px";
moveBox.style.top = y - mouseY + "px";
};
window.onmouseup = function(){
// 取消绑定的事件
window.onmousemove = null;
window.onmouseup = null;
};
return false;
};
</script>
</html>