每个复杂的运动效果都是由简单的效果组成的,我们可以为简单的效果制定一个框架,也就是写一个通用函数,这样可以对元素的任何属性进行变换,复杂的效果就可以很容易实现。
注意事项:
- 当变换元素的透明度时,需要做特殊处理
- 如果变换元素宽度时,对于有border的元素,如果我们使用obj.offsetWidth来取得元素宽度时,会出现错误,因为offsetWidth包括边框。如果边框是1px,定时函数中调用,obj.style.width=obj.offsetWidth-1+‘px’;,我们会发现元素的宽度不仅没有变小,反而会变大。这也是我们使用我们自定义的getStyle()取得元素宽度的原因,而没有使用offsetWidth这一类的属性。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>New Web Project</title>
<style>
div{
width:200px;
height:200px;
float:left;
background:red;
margin:10px;
}
</style>
<script>
function getStyle(obj,name)
{
if(obj.currentStyle)
{
return obj.currentStyle[name];
}
else
{
return getComputedStyle(obj,null)[name];
}
}
window.οnlοad=function(){
var objs=document.getElementsByTagName('div');
objs[1].οnmοuseοver=function(){
startMove(this,'width',400);
};
objs[1].οnmοuseοut=function(){
startMove(this,'width',200);
};
objs[0].οnmοuseοver=function(){
startMove(this,'height',400);
};
objs[0].οnmοuseοut=function(){
startMove(this,'height',200);
};
objs[2].οnmοuseοver=function(){
startMove(this,'opacity',100);
};
objs[2].οnmοuseοut=function(){
startMove(this,'opacity',30);
};
};
function startMove(obj,atrr,itarget){
clearInterval(obj.timer);
obj.timer=setInterval(function(){
var nowValue;
if(atrr=='opacity')
{
nowValue=Math.round(parseFloat(getStyle(obj,atrr))*100);//计算机运算会有错误,需要取约数
document.title=nowValue;
}
else
{
nowValue=parseInt(getStyle(obj,atrr));
}
var speed=(itarget-nowValue)/5;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(nowValue==itarget)
{
clearInterval(obj.timer);
}
else
{
if(atrr=='opacity')
{
obj.style[atrr]=(nowValue+speed)/100;
obj.style.filter='alpha(opacity:'+(nowValue+speed)+')';//IE低版本设置
}
else
{
obj.style[atrr]=nowValue+speed+'px';
}
}
},30);
}
</script>
</head>
<body>
<div></div>
<div></div>
<div style="opacity: 0.3; filter: alpha(opacity:30);"></div>
</body>
</html>
运行效果图: