<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>完美拖拽</title>
<style type="text/css">
html,body{overflow:hidden;}
body,div,h2,p{margin:0;padding:0;}
body{color:#fff;background:#000;font:12px/2 Arial;}
p{padding:0 10px;margin-top:10px;}
span{color:#ff0;padding-left:5px;}
#box{position:absolute;300px;height:150px;background:#333;border:2px solid #ccc;top:50%;left:50%;margin:-75px 0 0 -150px;}
#box h2{height:25px;cursor:move;background:#222;border-bottom:2px solid #ccc;text-align:right;padding:0 10px;}
#box h2 a{color:#fff;font:12px/25px Arial;text-decoration:none;outline:none;}
</style>
</head>
<body>
<div id="box" style="margin-left: 0px; margin-top: 0px; left: 533px; top: 231px;">
<h2><a href="javascript:;" id="a1">点击回放拖动轨迹</a></h2>
<p><strong>Drag:</strong><span>false</span></p>
<p><strong>offsetTop:</strong><span>231</span></p>
<p><strong>offsetLeft:</strong><span>533</span></p>
</div>
</body>
</html>
<script>
window.onload = function(){
var oDiv = document.querySelector("#box");
var oA1 = document.getElementById("a1");
var arr = [];
oDiv.onmousedown = function(e){
var e = e || event;
var disx = e.offsetX;
var disy = e.offsetY;
document.onmousemove = function(e){
var e = e || event;
var x = e.pageX - disx;
var y = e.pageY - disy;
var maxL = window.innerWidth - 300;//最大的left
var maxT = window.innerHeight- 150;//最大的top
if( x<0 ){ //左边界
x = 0;
}else if( x > maxL ){ //右边界
x = maxL;
}
if( y<0 ){ //上边界
y = 0;
}else if( y > maxT ){ // 下边界
y = maxT;
}
oDiv.style.left = x + "px";
oDiv.style.top = y + "px";
var pos = {
aleft : x,
atop : y
}
arr.unshift( pos );
}
document.onmouseup = function(){
document.onmousemove = null;
oA1.onclick = function(){
var num=0;
var timer = null;
timer = setInterval(function(){
oDiv.style.left = arr[num].aleft + "px";
oDiv.style.top = arr[num].atop + "px";
num++;
if(num == arr.length){
clearInterval(timer);
arr = [];
return;
}
},100);
};
}
}
}
</script>