<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>颜色的淡入淡出</title>
<style>
#div1{
width: 200px;
height: 200px;
background-color: blue;
opacity: 0.3;
filter: alpha(opcaity=30);
}
</style>
</head>
<body>
<div id="div1"></div>
<!--
<script>
var oDiv = document.getElementById("div1");
oDiv.alpha = 30;
var timer = null;
oDiv.addEventListener("mouseover",function(){
timer = setInterval(function(){
if(oDiv.alpha == 100){
clearInterval(timer);
}else{
oDiv.style.opacity = (oDiv.alpha + 10)/100 ;
oDiv.alpha = oDiv.alpha + 10;
}
},30);
});
</script>
-->
<!--
<script>
var oDiv = document.getElementById("div1"),
alpha = 30,
timer = null;
oDiv.addEventListener("mouseover",function(){
timer = setInterval(function(){
if(alpha == 100){
clearInterval(timer);
}else{
alpha = alpha + 10;
oDiv.style.opacity = alpha/100;
}
},30);
});
</script>
-->
<script>
var oDiv = document.getElementById("div1"),
alpha = 30,
timer = null;
/*
alpha:
speed:
*/
function startMove(iTarget,speed){
clearInterval(timer);
timer = setInterval(function(){
// if(speed > 0){
// if(alpha == iTarget){
// clearInterval(timer);
// }else{
// alpha = alpha + speed;
// oDiv.style.opacity = alpha/100;
// }
// }else{
// if(alpha == iTarget){
// clearInterval(timer);
// }else{
// alpha = alpha + speed;
// oDiv.style.opacity = alpha/100;
// }
// }
//这里的判断语句实际上是:到目标点了吗,到了,管它透明度是100还是30,都给我清空定时器;没到?那就靠speed来控制是增加透明度还是减少透明度咯.嗯,很简单!
//只不过,在这里,我们的实现方式与官方版本稍微有点不一样,官方版本的startMove()函数对外提供了一个形参,而我们的startMove()函数对外提供了两个形参!
if(alpha == iTarget){
clearInterval(timer);
}else{
alpha = alpha + speed;
oDiv.style.opacity = alpha/100;
}
},30);
}
//鼠标移入事件
oDiv.addEventListener("mouseover",function(){
startMove(100,10);
});
//鼠标移出事件
oDiv.addEventListener("mouseout",function(){
startMove(30,-10);
});
</script>
</body>
</html>