<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>匀速改变div的透明度</title>
<style>
#box {
width: 100px;
height: 100px;
background: red;
position: absolute;
left: 0;
top: 100px;
opacity:0.3;
}
</style>
</head>
<body>
<div id="box"></div>
<script src="tool.js"></script>
<script>
var obox = ById('box');
var timer = null;
var alpha =30;
obox.onmouseover = function(){
opacitymove(100);
}
obox.onmouseout = function(){
opacitymove(30);
}
function opacitymove(target){
clearInterval(timer);
timer = setInterval(function(){
var speed = target - alpha > 0 ? 1 : -1;
if(target == alpha){
clearInterval(timer);
}else{
alpha += speed; //30秒后透明度从30变成40,再30秒后透明度从40变成50,依次递增,所以+=speed.
obox.style.opacity = alpha/100;
}
},30)
}
</script>
</body>
</html>