一、Html布局
<body>
<div id="mydiv">
</div>
</body>
二、Css样式
<style>
body{
margin:0;
padding: 0;
}
#mydiv{
width: 200px;
height:200px;
background:red;
filter:alpha(opacity:30); /*针对 IE8 以及更早的版本*/
opacity:0.3;
}
</style>
三、Js部分
<script>
window.onload = function(){
var oDiv = document.getElementById("mydiv");
oDiv.onmouseover = function(){
startMove(100);
}
oDiv.onmouseout = function(){
startMove(30);
}
}
var timer = null;
//定义定时器
var alpha = 30;
//定义透明度
startMove = function(iTarget){
clearInterval(timer);
//开启定时器前先关闭所有定时器
var oDiv = document.getElementById("mydiv");
timer = setInterval(function(){
var speed = 0;
if(alpha > iTarget){
speed = -10;
}else{
speed = 10;
}
if(alpha == iTarget){
clearInterval(timer);
}else{
alpha += speed;
oDiv.style.filter = 'alpha(opacity: '+alpha+')';
//针对 IE8 以及更早的版本
oDiv.style.opacity = alpha/100;
}
},30)
}
</script>