<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
div {
150px;
height: 150px;
background: red;
float: left;
margin: 10px;
font-size: 8px;
filter: alpha(opacity: 30);
opacity: 0.3;
}
</style>
<script>
var timer = null;
window.onload = function() {
//******************************************
var div1 = document.getElementById('div1');
div1.timer = null;
div1.onmouseover = function() {
startMove(div1, 'opacity', 100);
}
div1.onmouseout = function() {
startMove(div1, 'opacity', 30);
}
};
function getStyle(obj, name) {
if(obj.currentStyle) {
return obj.currentStyle[name];
} else {
return getComputedStyle(obj, false)[name];
}
}
function startMove(obj, element, target) {
clearInterval(obj.timer);
obj.timer = setInterval(function() {
var crrent = 0;
//增加if else语句,判断opacity
if(element == 'opacity') {
//round四舍五入
crrent = Math.round(parseFloat(getStyle(obj, element))*100);
} else {
crrent = parseInt(getStyle(obj, element));
}
var speed = (target - crrent) / 5500;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
if(crrent == speed) {
clearInterval(obj.timer);
} else {
if(element == 'opacity') {
obj.style.filter = 'alpha(opacity:' + (crrent + speed)+ ')';
obj.style.opacity = (crrent + speed) / 100;
} else {
obj.style[element] = crrent + speed + 'px';
}
}
}, 30);
}
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>