<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#box1{
width:100px;
height:100px;
background: orangered;
position: absolute;
}
#box2{
width:100px;
height:100px;
background: hotpink;
position: absolute;
left:110px;
}
img{
width:100px;
height:100px;
position: absolute;
left:220px;
}
</style>
</head>
<body>
<div id="box1"></div>
<div id="box2"></div>
<img src="img/1.jpg" id="img" />
<script>
drag("box1");
drag("box2");
drag("img");
function drag(id){
var obj = document.getElementById(id);
obj.onmousedown=function(evt){
var e = evt || window.event;
var disX=e.offsetX;
var disY=e.offsetY;
document.onmousemove=function(evt){
evt = evt || window.event;
obj.style.left=evt.pageX-disX+'px';
obj.style.top=evt.pageY-disY+'px';/获取对象的左边定位=当前事件绝对位置-相对位置
}
document.onmouseup=function(){
document.onmousemove=null;
}
document.ondragstart=function(){
return false;
}
}
}
</script>
</body>