效果:按下鼠标拖动其位置,松开鼠标停止
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin: 0;
padding: 0;
}
#box{
width: 80px;
height: 80px;
background: #00A7F6;
position: absolute;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
var box=document.getElementById("box");
box.onmousedown=function (ev) {
var even=window.event||ev;
// 鼠标实际坐标减去方块左上角坐标,即鼠标在距方块的距离,使松开鼠标时在其实际位置,而不是左上角
var x=box.offsetLeft-even.clientX;
var y=box.offsetTop-even.clientY;
document.onmousemove=function (ev) {
var even=window.event||ev;
box.style.top=even.clientY+y+'px';
box.style.left=even.clientX+x+'px';
}
document.onmouseup=function () {
document.onmousedown=null;
document.onmousemove=null
}
}
</script>
</body>
</html>