效果:鼠标移入时,图片由半透明逐渐变成清晰,移出时,由清晰变为半透明
分析:用变量来储存透明度,因为元素.style.alpha不能直接增加或减少
代码中另附有一个设置元素透明度的方法, 是按IE规则(0~100)设置, 若改成标准设置方法(0.00~1.00)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
body{
margin: 100px;
}
img{
display: block;
width: 640px;
height: 350px;
opacity:30;
filter: alpha(opacity:30);
}
</style>
</head>
<body>
<img src="img/4.jpg" alt="" />
</body>
<script type="text/javascript">
(function(){
var oImg = document.querySelector('img');
var alpha = 30;
oImg.onmouseover = function(){show(100,5) ;}
oImg.onmouseout = function(){show(30,-5); }
var handler = null;
function show(target,speed){
clearInterval(handler);
handler = setInterval(function(){
if(alpha == target){
clearInterval(handler);
}
else {
alpha+=speed;
oImg.style.opacity = alpha/100;
oImg.style.filter = 'alpha(opacity:' + alpha +')';
}
},60)
}
})()
</script>
</html>