<!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;width: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>
<script type="text/javascript">
window.onload=function(){
var box=document.getElementById("box");
var posx=document.getElementsByClassName("posx")[0];
var posy=document.getElementsByClassName("posy")[0];
var h=box.children[0];
var hf=h.children[0];
var pos;//将pos设为全局变量
var posArray=[];//定义一个空数组,记录每次移动的坐标
function move (e){//将move函数提到外面
var e=e||event;
box.style.left=e.clientX-pos.x+"px";
box.style.top=e.clientY-pos.y+"px";
posx.innerText=parseInt(box.style.left);
posy.innerText=parseInt(box.style.top);
posArray.push({
left:box.style.left,
top:box.style.top
});
}
h.addEventListener("mousedown",function(e){
var e=e||event;
pos={
x:e.offsetX,
y:e.offsetY
};
document.addEventListener("mousemove",move)
})
document.addEventListener("mouseup",function(){
document.removeEventListener("mousemove",move);
})
hf.addEventListener("click",function(){
var timer=setInterval(function(){
current=posArray.pop();
while(!current){
clearInterval(timer);
return ;
}
box.style.left=current.left;
box.style.top=current.top;
posx.innerText=parseInt(box.style.left);
posy.innerText=parseInt(box.style.top);
},10)
})
};
</script>
</head>
<body>
<div id="box" style="margin-left: 0px; margin-top: 0px; left: 533px; top: 231px;">
<h2><a href="javascript:;">点击回放拖动轨迹</a></h2>
<p><strong>你好:</strong><span class="isdrag">加油</span></p>
<p><strong>offsetTop:</strong><span class="posx">231</span></p>
<p><strong>offsetLeft:</strong><span class="posy">533</span></p>
</div>
</body></html>
元素拖拽及回放
猜你喜欢
转载自blog.csdn.net/qq_43031907/article/details/82085576
今日推荐
周排行