向上取整和向下取整
<!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>无标题文档</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);
当物体宽度为200,目标为400时,speed的值应该是从200/8一直变到0。比如,由于像素问题,变道0.5就不在变化了,那么就要把0.5变为0.此时应该是向下取整,也就是Math.floor(speed)。同理,当从400变为200时,speed的值一直是负的,比如,到最后变为-0.5不在变化,那么此时应该用向上取整使speed的值变为0啊。所以,这句speed = speed>0?Math.ceil(speed):Math.floor(speed);为什么不是speed = speed>0?Math.floor(speed):Math.ceil(speed);