问答详情
源自:2-2 JS透明度动画

透明度opacity值不稳定

<!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">

#boss{

width:300px;

height:300px;

background:#CF3;

opacity:0.3}

</style>

<script type="text/javascript">

window.onload=function(){

var boss=document.getElementById('boss'),timer=null,alpha=30;

boss.onmouseover=function()

{

opa(100);

}

boss.onmouseout=function()

{

opa(30);

}

function opa(itarget){

clearInterval(timer);

timer=setInterval(function(){

var speed=0;

if(alpha>itarget)

speed=-10;

else 

speed=10;

if(boss.style.opacity==itarget)

clearInterval(timer);

else{

alpha+=speed;

boss.style.filter='alpha(opactiy:'+alpha+');'

boss.style.opacity=alpha/100;

}

},30)

}

}

</script>

</head>


<body>

<div id="boss">

</div>

</body>

</html>

我的代码,和老师讲的几乎一样啊,为什么透明度在1和0.3左右的一直在变

提问者:Dream0703 2016-05-12 16:15

个回答

  • 权哲
    2016-05-12 16:51:16
    已采纳

    if(boss.style.opacity==itarget)

    clearInterval(timer);

     这块没能清除 计时器,

    boss.style.opacity 他算出的是浮点数就是0.3不可能等于itarget30。把他换成alpha 就好了。