由于JS里对于数值小数点会自动去除,所以对于运动位置,需要使用Math.ceil()向上取整或者
Math.floor()向下取整进行解决
以下是我的缓冲运动练习简单代码
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>
#div1{width:200px;height:200px;background:red;left:0px;top:50px;position:absolute;}
#div2{width:1px;height:250px;background:black;left:400px;top:20px;position:absolute;}
</style>
<script>
window.onload=function ()
{
var oDiv=document.getElementById('div1');
var oBtn=document.getElementById('btn1');
oBtn.onclick=function ()
{
startMove(400);
}
};
var timer=null;
function startMove(target)
{
var oDiv=document.getElementById('div1');
var speed=0;
clearInterval(timer)
timer=setInterval(function ()
{
//speed会被直接取整,舍去余数,所以位置不精确,需要通过向上取整Math.ceil()来解决
speed=Math.ceil((target-oDiv.offsetLeft)/10);
oDiv.style.left=oDiv.offsetLeft+speed+'px';
document.title=oDiv.offsetLeft+','+speed;
},30);
};
</script>
</head>
<body>
<input id="btn1" type="button" value="开始运动" />
<div id="div1">
</div>
<div id="div2">
</div>
</body>
</html>