向上取整和向下取整
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標(biāo)題文檔</title>
<style type="text/css">
*{margin:0;padding:0;}
ul li{
list-style:none;
width:200px;
height:100px;
background:yellow;
margin-bottom:20px;
}
</style>
<script type="text/javascript">
? window.onload=function(){
?var ali = document.getElementsByTagName("li");
?for(i=0;i<ali.length;i++){
?ali[i].timer = null;
?ali[i].onmouseover=function(){
?startMove(this,400);
?}
?ali[i].onmouseout=function(){
?startMove(this,200);
?}
?}
? }
? function startMove(obj,itarget){
?clearInterval(obj.timer);
?var speed;
?obj.timer=setInterval(function(){
?speed = (itarget-obj.offsetWidth)/8;
? ? ?speed = speed>0?Math.ceil(speed):Math.floor(speed);
?if(obj.offsetWidth == itarget){
?clearInterval(obj.timer);
?}
?else{
?obj.style.width = obj.offsetWidth+speed+"px";
?}
?},30);
? }
</script>
</head>
<body>
<ul>
? <li></li>
? <li></li>
? <li></li>
</ul>
</body>
</html>
這兩行:
speed = (itarget-obj.offsetWidth)/8;
speed = speed>0?Math.ceil(speed):Math.floor(speed);
當(dāng)物體寬度為200,目標(biāo)為400時(shí),speed的值應(yīng)該是從200/8一直變到0。比如,由于像素問題,變道0.5就不在變化了,那么就要把0.5變?yōu)?.此時(shí)應(yīng)該是向下取整,也就是Math.floor(speed)。同理,當(dāng)從400變?yōu)?00時(shí),speed的值一直是負(fù)的,比如,到最后變?yōu)?0.5不在變化,那么此時(shí)應(yīng)該用向上取整使speed的值變?yōu)?啊。所以,這句speed = speed>0?Math.ceil(speed):Math.floor(speed);為什么不是speed = speed>0?Math.floor(speed):Math.ceil(speed);
2015-12-26
你是把最終的結(jié)果取整了,而實(shí)際上是把每次運(yùn)動(dòng)時(shí)的速度取整了。
10每次減0.9一直減減到0.1,然后向下取整,但實(shí)際是先把0.9向上取整為1,然后一直減減到0。好像是這樣
2015-12-26
speed值應(yīng)該是從200/8變道1的,如果寬度差值為4,speed為0.5,如果這時(shí)向下取整得到0,那么寬度不變,就一直維持著4的差值,達(dá)不到400px,所以speed至少為1;