所谓步长就是去做一件事情规定时间内分特定的步数走完。
做一个小demo
让红色的方块移动到黑色线里面去,给红色小方块一个终点,定时器每次启动的时候(50毫秒)移动一次,如过我们想让他移动慢点就可以做一个判断让速度变慢 这个变慢就是步长的核心思想 把他总长度分多少段走完。下面是代码和移动后的效果
在这里插入代码片
```<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style>
div {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 0px;
top: 0;
}
#btn {
margin-top: 150px;
}
span {
position: absolute;
width: 1px;
height: 100px;
background-color: black;
left: 500px;
top: 0;
}
</style>
<body>
<div></div>
<span></span>
<button id="btn">run</button>
<script>
var div = document.getElementsByTagName("div")[0];
var btn = document.getElementById("btn");
var timer = null;
btn.onclick = function() {
move(div, 500)
}
function move(ele, target) {
clearInterval(timer);
var ispeed = target - ele.offsetLeft > 0 ? 7 : -7;
timer = setInterval(function() {
//最后一步剩余的距离小于我们的移动的距离ispeed
if (Math.abs(target - ele.offsetLeft) < Math.abs(ispeed)) {
clearInterval(timer)
ele.style.left = target + 'px';
} else {
ele.style.left = ele.offsetLeft + ispeed + 'px';
}
}, 30)
}
</script>
</body>
</html>