<!DOCTYPE HTML>
<html>
<head>
<title>offset案例:鼠标拖动盒子移动</title>
<meta charset="utf-8" />
<style>
* {
margin: 0;
padding: 0;
}
#box {
position: relative;
width: 200px;
height: 200px;
background-color: pink;
cursor: move;
}
</style>
</head>
<body>
<div id="box"> </div>
<script>
var box = document.getElementById('box');
box.addEventListener('mousedown', function(e) {
var x1 = e.pageX - box.offsetLeft;
var y1 = e.pageY - box.offsetTop;
document.addEventListener('mousemove', move)
function move(e) {
var x2 = e.pageX - x1;
var y2 = e.pageY - y1;
box.style.left = x2 + 'px';
box.style.top = y2 + 'px';
}
document.addEventListener('mouseup', function() {
document.removeEventListener('mousemove',move);
})
})
</script>
</body>
</html>