<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
div{
150px;
height: 150px;
background: red;
margin: 5px;
float: left;
filter: alpha(opacity:30);
opacity: 0.3;
}
</style>
<script>
window.onload = function(){
var divs = document.getElementsByTagName('div');
for(var i=0;i<divs.length;i++){
//添加属性
divs[i].timer = null;
divs[i].alpha = 30;
divs[i].onmouseover = function(){
startmoveDiv(this,100);
};
divs[i].onmouseout = function(){
startmoveDiv(this,30);
};
}
};
function startmoveDiv(obj,target){
//清除之前的定时器(保证同一时间一个物体上只存在一个定时器,不然几个定时器累加,速度会变得很快)
clearInterval(obj.timer);
obj.timer = setInterval(function(){
//获得变化的速度
var speed = (target - obj.alpha)/70;
//将速度取整
speed = speed>0?Math.ceil(speed):Math.floor(speed);
if(obj.alpha == target){
clearInterval(obj.timer);
}else{
obj.alpha += speed;
//一下是兼容性的体现,支持几种浏览器
obj.style.filter = 'alpha(opacity:'+obj.alpha+')';
obj.style.opacity = obj.alpha/100;
}
},30);
}
</script>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
</body>
</html>