不寫Math.round()得到的是整數(shù)還有必要寫嗎
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
*{margin:0;
?padding:0;}
div{width:200px;
height:200px;
background:red;
float:left;
margin:10px;
filter:alpha(opacity:30);
opacity:0.3;}
li{width:200px;
height:100px;
background:yellow;
margin:10px;
margin-left:0;
list-style:none;
position:relative;
top:220px;
border:10px solid red;}
</style>
<script>
window.onload=function(){
var div=document.getElementById('div1')
div.onmouseover=function(){
startMove(this,'opacity',100);
}
div.onmouseout=function(){
startMove(this,'opacity',30);
}
}
function getStyle(obj,attr){
if(obj.currentStyle){
return obj.currentStyle[attr];
}else{
return getComputedStyle(obj,false)[attr];
}
}
function startMove(obj,attr,iTarget){
clearInterval(obj.timer);
obj.timer=setInterval(function(){
if(attr=='opacity'){
var iCur=parseFloat(getStyle(obj,attr))*100;
}else{
var iCur=parseInt(getStyle(obj,attr));
}
//alert(iCur);
var speed=(iTarget-iCur)/20
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(iTarget==iCur){
clearInterval(obj.timer)
}else{
if(attr=='opacity'){
obj.style.opacity=(iCur+speed)/100;
}else{
obj.style[attr]=iCur+speed+'px'
}
}
},30)
}
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>
2016-09-11
根據(jù)你輸入的數(shù)值,在進(jìn)行計(jì)算時(shí)(例如:浮點(diǎn)數(shù)乘以整數(shù)),瀏覽器對(duì)其進(jìn)行識(shí)別,有時(shí)會(huì)出現(xiàn)一些不易發(fā)現(xiàn)的Bug(例如:視頻中出現(xiàn)的0.07*100得到的結(jié)果是7.00000000001)。
為了在數(shù)值上完全避免Bug。
建議您還是用Math.round()來處理下最終數(shù)值。
保持良好的細(xì)節(jié)處理習(xí)慣可以增加開發(fā)效率。