Effect:
Ideas:
Use the Setinerval () timer for movement. Then the key point is to give it a fill gap when the final stop is judged.
Code:
Copy Code code as follows:
<title></title>
<style type= "Text/css" >
#div1
{
width:100px;
height:100px;
Background: #0000FF;
Position:absolute;
left:800px;
top:100px;
}
#div200
{
width:1px;
height:400px;
Background: #FF0000;
Position:absolute;
left:200px;
}
#div500
{
width:1px;
height:400px;
Background: #FF0000;
Position:absolute;
left:500px;
}
</style>
<script type= "Text/javascript" >
function Move (end) {
var odiv = document.getElementById (' Div1 ');
var timer = null;
Timer = setinterval (function () {
var speed = (end-odiv.offsetleft)/5; Take out the speed of motion according to the endpoint and offsetleft
Speed = speed > 0? Math.ceil (Speed): Math.floor (speed); Carry rounding, and decimal places become whole,
if (odiv.offsetleft <= end) {
Clearinterval (timer);
// }
else {
ODiv.style.left = odiv.offsetleft + speed + ' px ';
// }
if (Math.Abs (end-odiv.offsetleft) <= speed) {//due to a small gap at the end of the stop, or no complete arrival at the specified location, it is less than its speed
Clearinterval (timer); Let the timer stop when the distance is less than the speed
ODiv.style.left = end + ' px '; Fill the gap after stopping.
}
else {
ODiv.style.left = odiv.offsetleft + speed + ' px '; Move Div
}
}, 30)
}
</script>
<body>
<input type= "button" id= "Btn1" value= "to 500 position" onclick= "move (+);"/>
<input type= "button" id= "Btn2" value= "to 200 position" onclick= "move (MB);"/>
<div id= "Div1" >
</div>
<div id= "div200" >200
</div>
<div id= "div500" >500
</div>
</body>