Math.ceil(number)
向上取整
Math.ceil(3.0001) //4
Math.floor(number)
向下取整
Math.floor(3.99999) //3
緩沖運動,距離和速度成正比
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>緩沖運動</title>
<style>
*{
padding: 0;
margin: 0;
}
#btn{
position: absolute;
top: 150px;
left: 20px;
padding: 5px;
}
body div:first-of-type{
width: 100px;
height: 100px;
background: red;
position: absolute;
top: 200px;
}
body div:nth-of-type(2){
width: 1px;
height: 500px;
background: black;
position: absolute;
left: 400px;
}
</style>
<script>
window.onload = function(){
var btn = document.getElementById("btn");
var target = document.getElementsByTagName("div")[0];
var timer = null;
btn.onclick = function(){
move()
}
function move(){
clearInterval(timer);
timer = setInterval(function(){
var speed = (document.getElementsByTagName("div")[1].offsetLeft - target.offsetLeft)/10;
target.style.left = target.offsetLeft + speed + "px";
document.getElementsByTagName("span")[0].innerHTML = target.offsetLeft+ "," + speed;
}, 30);
}
}
</script>
</head>
<body>
<button id="btn">移動</button><span></span>
<div>
</div>
<div>
</div>
</body>
</html>
huanchong.gif
改1
speed = Math.ceil(speed);
huanchong2.gif
改1的問題
小紅塊的left設置改為700px后運行
huanchong3.gif
改2
speed = speed>0 ? Math.ceil(speed) : Math.floor(speed);
沒有問題了
huanchong4.gif