Effect:
Idea:
Use the setInerval() timer to perform exercise. Then the key point is to give it a judgment to fill the gap when it finally stops.
Code:
Copy the code code as follows:
<head runat="server">
<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; //Get the speed of movement based on the end point and offsetLeft
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed); //Carry rounding, the decimal place becomes an integer,
// if (oDiv.offsetLeft <= end) {
// clearInterval(timer);
// }
// else {
// oDiv.style.left = oDiv.offsetLeft + speed + 'px';
// }
if (Math.abs(end - oDiv.offsetLeft) <= speed) { //Because there will be a small gap in the end when stopping, or it does not completely reach the designated place, so it should be less than its speed
clearInterval(timer); //When the distance is less than the speed, stop the timer
oDiv.style.left = end + 'px'; //Fill the gap after stopping.
}
else {
oDiv.style.left = oDiv.offsetLeft + speed + 'px'; //Move DIV
}
}, 30)
}
</script>
</head>
<body>
<input type="button" id="btn1" value="To the position of 500" onclick="move(500);" />
<input type="button" id="btn2" value="To the position of 200" onclick="move(200);" />
<div id="div1">
</div>
<div id="div200">200
</div>
<div id="div500">500
</div>
</body>