<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>链式运动</title>
<style>
*{
padding:0;
margin:0;
list-style:none;
}
#box{
margin:0 auto;
background:orange;
width:200px;
height:200px;
opacity:0.3;
filter:alpha(opacity:30);
margin-bottom:20px;
}
</style>
<script>
window.onload=function(){
var div=document.getElementById("box");
div.onmouseover=function(){
change(this,'width',400,function(){
change(this,'height',400);
});
}
}
function getStyle(obj,attr){
if(obj.currentStyle){
return obj.currentStyle[attr];
}
else{
return getComputedStyle(obj,false)[attr];
}
}
function change(obj,attr,target,fn){
clearInterval(obj.timer);
obj.timer = setInterval(function(){
var val = 0;
if(attr == 'opacity'){
val = Math.round(parseFloat(getStyle(obj,attr))*100);
}
else{
val = parseInt(getStyle(obj,attr));
}
var speed = (target-val)/8;
speed = speed>0 ? Math.ceil(speed) : Math.floor(speed);
if(val == target){
clearInterval(obj.timer);
//判断是否传入了fn
if(fn){
fn();
}
}
else{
if(attr == 'opacity'){
obj.style.filter = 'alpha(opacity:' + val+speed + ')';
obj.style.opacity = (val+speed)/100;
}
else{
obj.style[attr] = val + speed +"px";
}
}
},30)
}
</script>
</head>
<body>
<div id="box"></div>
</body>
</html>