<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#box1{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
}
</style>
<script>
window.onload = function(){
var box1 = document.getElementById("box1");
//为鼠标绑定一个按下事件
box1.onmousedown = function(event){
event = event||window.event;
var ol = event.clientX - box1.offsetLeft;
var ot = event.clientY - box1.offsetTop;
document.onmousemove = function(event){
event = event||window.event;
var x = event.clientX-ol;
var y = event.clientY-ot;
//修改box的位置
box1.style.left = x+"px";
box1.style.top = y+"px";
};
};
document.onmouseup = function(){
//取消事件 在原地
document.onmousemove = null;
document.onmouseup;
}
};
</script>
</head>
<body>
<div id="box1"></div>
</body>
</html>