css code
The code copy is as follows:
<style type="text/css">
* {
margin: 0px;
padding: 0px;
font-family: "micsoft yahei", "Microsoft Yahei";
font-size: 15px;
}
div{
width: 50px;
height: 50px;
background: #f00;
border-radius:5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
cursor: pointer;
position: absolute;
top: 60px;
left: 30px;
}
input{
position: absolute;
top: 10px;
left: 10px;
padding: 3px;
cursor: pointer;
}
</style>
html code
The code copy is as follows:
<body>
<input type="button" value="Return in the original way"/>
<div></div>
</body>
javascript code
The code copy is as follows:
<script type="text/javascript">
//1. Start by clicking on the div with the mouse as the trigger.
//2. When clicking the mouse to move, trigger the mouse movement event to inject data into the array (move coordinates)
//3. End with the mouse moving away from the div as
//4. Click the "Original Return" button to traverse the array (moving coordinates) and trigger the coordinate movement of div in the array to achieve the "return" function.
window.onload=function(){
var oDiv=document.getElementsByTagName("div")[0];
var oBtn=document.getElementsByTagName("input")[0];
var time=null,arrTop=[],arrLeft=[];
oDiv.onmousedown=function(ev){
var event=ev || window.event;
//Get the coordinates of the mouse in the div
var disX=event.clientX-oDiv.offsetLeft;
var disY=event.clientY-oDiv.offsetTop;
arrTop=[60];
arrLeft=[30];
document.onmousemove=function(ev){
var event=ev || window.event;
//Get the mouse position after dragging
var l=event.clientX;
var t=event.clientY;
//Save the dragged position into the array, and use the dragged mouse position to subtract the mouse position on the object, which is the dragged object position.
arrLeft.push(l-disX);
arrTop.push(t-disY);
oDiv.style.left=l-disX +"px";
oDiv.style.top=t-disY +"px";
};
document.onmouseup=function(){
document.onmousemove=null;
document.onmouseup=null;
};
return false;
}
//The core of the original return is to record the coordinates when moving, then reorder the array, and set a timer to assign wide values in the array to the object.
oBtn.onclick=function(){
arrTop.reverse();//Reorder
arrLeft.reverse();//Reorder
var i=0;
oBtn.time=setInterval(function(){
oDiv.style.top=arrTop[i]+"px";
oDiv.style.left=arrLeft[i]+"px";
i++;
if(i==arrTop.length){
clearInterval(oBtn.time);
arrTop=[];
arrLeft=[];
}
},20);
}
}
</script>