用js写了一个移入移出的onmouseover和onmouseout的交互事件,但是只有onmouseover起作用,onmouseout无效,请问是哪里出了问题,我该如何去修改呢?
以下是代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>淡入淡出</title>
<script>
window.onload=function ()
{
var oDiv=document.getElementById('div1');
oDiv.onmouseover=function ()
{
demo(1);
};
oDiv.onmouseout=function ()
{
demo(0.3);
};
};
function demo(iTarget)
{
var oDiv=document.getElementById('div1');
var timer=null;
var alpha=0.3;
clearInterval(timer);
timer=setInterval(function ()
{
var speed=0;
if(alpha<iTarget)
{
speed= 0.1;
}
else
{
speed= -0.1;
}
if(alpha==iTarget)
{
clearInterval(timer);
}
else
{
alpha+=speed;
// oDiv.style.filter='alpha(opacity:'+alpha+')';
oDiv.style.opacity=alpha;
}
},30)
};
</script>
<style>
#div1
{
width: 200px;
height: 200px;
background: red;
/*filter: alpha(opacity:30);*/
opacity:0.3;
}
</style>
</head>
<body>
<div id="div1"></div>
</body>
</html>
这两个写在demo(iTarget)外面,另外最好是用整数加减,然后再除以100,小数加减会出现计算精度损失的