<!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">
</script>
</head>
<body>
<div id="box" style="margin-left: 0px; margin-top: 0px; left: 533px; top: 231px;">
<h2 id="tz"><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 src="../../../public.js"></script>
<script>
var box = document.getElementById("box");
var tz = document.getElementById("tz");
var btn=document.getElementById("a1");
? ? var arr=[];//保存位置信息
box.onmousedown = function (eve) {
var ee = eve || event;
var x = ee.offsetX;
var y = ee.offsetY;
var target = ee.target || ee.srcElement;
if (target.nodeName === "H2") {
document.onmousemove = function (eve) {
//改变box的位置
//值与移动时的鼠标所位置有关
var e = eve || event;
var l = e.pageX - x;
var t = e.pageY - y;
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
//解决移动鼠标过程中不小心选中文字后出现的bug。
//边界处理
//l最小为0 最大不能超过浏览器的宽-box的宽
//window.innerWidth
//window.innerHeight
var maxL = document.documentElement.clientWidth - 300;
var maxT = document.documentElement.clientHeight - 150;
l = l < 0 ? 0 : (l > maxL ? maxL : l);
t = t < 0 ? 0 : (t > maxT ? maxT : t);
box.style.left = l + "px";
box.style.top = t + "px";
arr.push([box.style.left,box.style.top]);//保存位置信息
}
}
}
document.onmouseup = function () {
document.onmousemove = null;
}
btn.onclick=function(){
var index=arr.length-1;//从后向前执行位置信息。
var timer=setInterval(function(){
box.style.left=arr[index][0];
box.style.top=arr[index][1];
index--;
if(index<0){
clearInterval(timer);
}
},10)
}
</script>
————————————————
版权声明:本文为CSDN博主「crazyFlex」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/crazyFlex/article/details/103517647