JS to achieve uniform motion code instance
- 2020-03-30 00:40:10
- OfStack
Effect:
< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201311/20131129164535664.gif" >
Ideas:
Exercise with the setInerval() timer. Then the key point is to give it a judgment to fill the gap at the end of the stop.
Code:
<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; //According to the end point and the velocity of offsetLeft fetch motion
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed); //Carry round, the decimal place becomes the whole place,
// if (oDiv.offsetLeft <= end) {
// clearInterval(timer);
// }
// else {
// oDiv.style.left = oDiv.offsetLeft + speed + 'px';
// }
if (Math.abs(end - oDiv.offsetLeft) <= speed) { //Because you end up with a small gap at the end of the stop, or you don't quite get there, it's going to be less than its speed
clearInterval(timer); //When the distance is less than the speed, let the timer stop
oDiv.style.left = end + 'px'; //Fill the gap after stopping.
}
else {
oDiv.style.left = oDiv.offsetLeft + speed + 'px'; //Mobile DIV
}
}, 30)
}
</script>
</head>
<body>
<input type="button" id="btn1" value=" to 500 The location of the " onclick="move(500);" />
<input type="button" id="btn2" value=" to 200 The location of the " onclick="move(200);" />
<div id="div1">
</div>
<div id="div200">200
</div>
<div id="div500">500
</div>
</body>