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

看以下代码,为什么mouseout后图像一直在闪?

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Examples</title>
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">
<style type="text/css">
	*{margin: 0;padding: 0;}
	#box{width: 200px;
		height: 200px;
		background-color: blue;
		opacity: 0.3;
		margin-left: 50px;}
</style>
</head>
<body>
    <div id = "box"></div>
<script type="text/javascript">
window.onload = function(){
	var box1 = document.getElementById('box');
	box1.onmouseover = function(){changeTo(1.0)};
	box1.onmouseout = function(){changeTo(0.3)};
}

var timer = null,alpha = 0.3;
function changeTo(a){
	clearInterval(timer);
	var box1 = document.getElementById('box');		
	timer = setInterval(function(){	
	if (alpha < a ){		
		alpha += 0.1;
		box1.style.opacity = alpha; }
	else if(alpha > a){
		alpha -= 0.1;
		box1.style.opacity = alpha; 
	}	
	else  {clearInterval(timer);}
	},300)
}

</script>
</body>
</html>


提问者:weibo_尛进进_04125716 2016-12-06 15:42

个回答

  • 王小毓
    2016-12-07 17:08:27

    按照老师的做法  把透明度改成100、 30 然后最后设定时去除以100即可。可能是因为底层JS运算小数的时候因为进制关系无法准确算到0.3或者1.0……

  • qq_小叮当_2
    2016-12-06 16:28:06

    透明度到底是为了变为0.1还是0.3?

  • qq_Mryesterday_14163005
    2016-12-06 16:04:08

    把定时器的时间值设置小点