- 完美拖拽点击记录运动轨迹返回原位置
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box{
width: 300px;
height: 200px;
background: #999;
position: absolute;
left: 0;
top: 0;
}
.title{
width: 100%;
height: 20px;
background: black;
position: absolute;
left: 0;
top: 0;
}
.title span{
width: 30px;
height: 20px;
background: red;
color: yellow;
position: absolute;
top: 0;
right: 0;
font-size: 12px;
}
.msg{
width: 100%;
height: 180px;
background: yellowgreen;
position: absolute;
left: 0;
top: 20px;
color: blue;
}
</style>
</head>
<body>
<div id="box">
<div class="title">
<span>返回</span>
</div>
<div class="msg"></div>
</div>
<script>
var o_box = document.querySelector('#box');
var o_back = document.querySelector('.title span');
var arr = [];
o_box.onmousedown = function(evt){
var e = evt || window.event;
var target = e.target || e.srcElement;
if(target.className === 'title'){
var dis_x = e.offsetX;
var dis_y = e.offsetY;
document.onmousemove = function(evt){
var e = evt || window.event;
var left = e.pageX - dis_x;
var top = e.pageY - dis_y;
if(left <= 0){
left = 0;
}else if(left >= document.documentElement.clientWidth - o_box.offsetWidth){
left = document.documentElement.clientWidth - o_box.offsetWidth;
}
if(top <= 0){
top = 0;
}else if(top >= document.documentElement.clientHeight - o_box.offsetHeight){
top = document.documentElement.clientHeight - o_box.offsetHeight;
}
o_box.style.left = left + 'px';
o_box.style.top = top + 'px';
arr.push({left : o_box.offsetLeft,top : o_box.offsetTop});
console.log(arr);
}
document.onmouseup = function(){
document.onmousemove = null;
}
document.ondragstart = function(){
return false;
}
}
}
o_back.onclick = function(){
var index = arr.length - 1;
var timer = setInterval(function(){
o_box.style.left = arr[index].left + 'px';
o_box.style.top = arr[index --].top + 'px';
if(index === -1){
clearInterval(timer);
}
}, 30);
}
</script>
</body>
</html>