話不多說饲宿;直接上代碼(復(fù)制粘貼即可使用)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#box{
width: 100px;
height: 100px;
background: red;
position: absolute;
}
</style>
</head>
<body>
<input type="button" name="btn" id="btn" value="回到原點(diǎn)" />
<div id="box">
</div>
<script type="text/javascript">
var arr = [];
function drag(obj){
obj.onmousedown = function(evt){
arr = [];
var e = evt || window.event;
//獲取鼠標(biāo)的相對(duì)于對(duì)象的坐標(biāo)值
var disX = e.offsetX;
var disY = e.offsetY;
document.onmousemove = function(evt){
var e = evt || window.event;
//求出對(duì)象到頁面邊的距離
var left = e.pageX - disX;
var top = e.pageY - disY;
//設(shè)置邊界
//左右邊界
if(left <= 0){
left = 0;
}else if(left >= document.documentElement.clientWidth - obj.offsetWidth){
left = document.documentElement.clientWidth - obj.offsetWidth;
}
//上下邊界
if(top <= 0){
top = 0;
}else if(top >= document.documentElement.clientHeight - obj.offsetHeight){
top = document.documentElement.clientHeight - obj.offsetHeight;
}
//設(shè)置對(duì)象的坐標(biāo)值
obj.style.left = left + "px";
obj.style.top = top + "px";
console.log({"left":obj.offsetLeft,"top" : obj.offsetTop});
//記錄下對(duì)象運(yùn)動(dòng)的軌跡
arr.push({"left":obj.offsetLeft,"top" : obj.offsetTop});
}
//取消移動(dòng)事件
document.onmouseup = function(){
document.onmousemove = null;
}
//刪除拖拽的默認(rèn)行為
document.ondragstart = function(){
return false;
}
}
}
var oBox = document.getElementById("box");
var oBtn = document.getElementById("btn");
oBtn.onclick = function(){
var index = arr.length - 1;
var timer = setInterval(function(){
if(index < 0){
clearInterval(timer);
arr = [];
}else{
oBox.style.left = arr[index].left + "px";
oBox.style.top = arr[index].top + "px";
index --;
}
},30)
}
drag(oBox);
</script>
</body>
</html>