拖拽元素,点击按钮,按拖拽轨迹回放拖拽过程
html
<div id="box" style="margin-left: 0px; margin-top: 0px; left: 533px; top: 231px;">
<h2>
<a href="javascript:;">点击回放拖动轨迹</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>
CSS
<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;
line-height: 25px;
}
#box h2 a {
color: #fff;
font: 12px/25px Arial;
text-decoration: none;
outline: none;
}
</style>
JS
<script>
var box = document.querySelector('#box');
var a = document.querySelector('a');
// console.log(box);
//获取最大边界值
var x = window.innerWidth;//窗口的宽度
var y = window.innerHeight;//窗口的高度
//盒子的实际宽高
var divx = box.offsetWidth;
var divy = box.offsetHeight;
//盒子移动的最大边界应该为窗口的宽高减去盒子的实际宽高
var maxX = x - divx;
var maxY = y - divy;
var arryTop;
var arryLeft;
//鼠标按下,在盒子上 获取鼠标的位置
box.addEventListener('mousedown', fn);
function fn(eve) {
//获取鼠标距离父元素的坐标
var ox = eve.offsetX;
var oy = eve.offsetY;
//鼠标每次按下,清空数组中上次移动的数据
arryTop = [];
arryLeft = [];
document.onmousemove = function (e) {
e = e || window.event;
//鼠标距离文档的坐标
var px = e.pageX;
var py = e.pageY;
//保证移动时鼠标和元素之间的位置不变,同时是移动时移动元素的坐标
var tmpX = px - ox;
var tmpY = py - oy;
//如果盒子距左边的距离小于0
if (tmpX < 0) {
tmpX = 0;//设置距离为0
}
//如果盒子距上方的距离小于0
if (tmpY < 0) {
tmpY = 0;//设置距离为0
}
//如何盒子距离右边的距离大于最大宽度
if (tmpX > maxX) {
tmpX = maxX;//设置距离为最大宽度
}
//如何盒子距离左边的距离大于最大高度
if (tmpY > maxY) {
tmpY = maxY;//设置距离为最大高度
}
// 设置样式
box.style.top = tmpY + 'px';
box.style.left = tmpX + 'px';
//将坐标保存进对应数组
arryTop.push(tmpY);
arryLeft.push(tmpX);
}
}
//鼠标抬起时,清除移动事件
document.onmouseup = function () {
document.onmousemove = '';
}
//a的单击事件同样会触发盒子的鼠标按下事件,鼠标按下时会清空保存坐标的数组数据,
//所以要阻止事件冒泡,避免点击回放时,清空数组数据导致无法回放
//阻止事件冒泡
a.addEventListener('mousedown',fn1);
function fn1(eve){
eve.stopPropagation();
}
a.onclick = function () {
var times = '';//定时器
var index = arryLeft.length;//x长度
console.log(index);
times = setInterval(function () {
index--;
box.style.top = arryTop[index] + 'px';
box.style.left = arryLeft[index] + 'px';
if (index == 0) {
clearInterval(times);
arryLeft = [];
arryTop = [];
}
}, 30)
}
</script>