<!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>
div{
width:200px;
height:200px;
background:#F00;
opacity:1;
}
</style>
<script>
window.onload=function(){
var div=document.getElementsByTagName('div')[0];
div.onmouseover=function(){
biantmd();
}
}
var tmd=1;
var timer=null;
function biantmd(){
var div=document.getElementsByTagName('div')[0];
clearInterval(timer);
timer=setInterval(function(){
if(tmd==0.3){
clearInterval(timer);
}else{
tmd=tmd-0.1;
div.style.opacity=tmd;
}
//clearInterval(timer);
},30);
}
</script>
</head>
<body>
<div></div>
</body>
</html>
思路上分析,可以肯定问题出现在条件判断上,即tmd == 0.3这个条件从来没成立过,实际上是永不成立,这是浮点数的锅。目前一切语言的浮点数计算都是近似计算,会精确到小数点16位以上。所以对于浮点数变量tmd来说,人为感觉是 tmd == 0.3的时候, tmd实际值则是 0.300000000000001之类的值,所以不等。想要看清tmd实际值,只需在 tmd = tmd - 0.1;这句话后面加alert(tmd),就看得一清二楚。
if(tmd<=0.3){
clearInterval(timer);
}
onmouseout