以下代码就不详细解析了,在我之前的多个运动效果中已经解析好多次了,重复的地方这里就不说明了,有兴趣的童鞋可以去看看之前的文章《原生javascript的小特效》
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
body,*{margin: 0;padding: 0;}
li{width: 300px;height:100px;background: yellow;margin-top: 10px;filter: alpha(opacity:30);opacity: 0.3}
</style>
<script type="text/javascript">
window.onload=function(){
var aLi=document.getElementsByTagName("li")[0];
aLi.onmouseover=function(){
onOut(aLi,500,'width',function(){ //我们把一个匿名函数作为参数传进,函数同样执行 onOut()函数
onOut(aLi,300,'height');
});
}
aLi.onmouseout=function(){
onOut(aLi,100,'height',function(){
onOut(aLi,300,'width');
});
}
}
function onOut(that,tag,tagattr,fun){
clearInterval(that.timer);
that.timer=setInterval(function(){
var speed;
var attr;
if(tagattr=='opacity'){
attr=Math.round(parseFloat(getAttr(that,tagattr)));
//计算机在处理小数点的时候不是很准确的,一般这样我们都四舍五入一下
}else{
attr=parseInt(getAttr(that,tagattr));
}
if(tagattr=='opacity'){
speed=(tag-attr);
}
else{
speed=(tag-attr)/20;
}
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(attr==tag){
clearInterval(that.timer);
if(fun){ //判断是否有fun参数传进来
fun();// 链式运动中我们在停止上一次运动的时候,来个判断,是否有fun这个函数,有的话 就执行
}
}else{
if(tagattr=='opacity'){
that.style.filter="alpha(opacity:'+speed+')";
that.style.opacity=speed/100;
}else{
that.style[tagattr]=attr+speed+"px";
}
}
},20)
}
function getAttr(obj,attr){
var style;
if(obj.currentStyle){
style=obj.currentStyle[attr];
}else{
style=getComputedStyle(obj,false)[attr];
}
return style;
}
</script>
</head>
<body>
<ul>
<li></li>
</ul>
</body>
</html>