淡入淡出实现
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#box {width:200px; height:200px; background:red;}
</style>
</head>
<body>
<div id="box">
</div>
<br />
<button>淡出</button>
<button>淡入</button>
<script type="text/javascript">
var box = document.getElementById('box');
var btns = document.getElementsByTagName('button');
var t = null; //定时器
//淡出
btns[0].onclick = function(){
clearInterval(t);
var opa = 1; //默认初识值
t = setInterval(function(){
opa -= 0.05;
box.style.opacity = opa;
console.log(opa);
if (opa <= 0) {
opa = 0; //校正一下
clearInterval(t);
}
},100);
}
//淡入
btns[1].onclick = function(){
clearInterval(t);
var opa = 0; //默认初始值
t = setInterval(function(){
opa += 0.05;
box.style.opacity = opa;
if (opa >= 1) {
opa = 1;
clearInterval(t);
}
},100);
}
</script>
</body>
</html>