用js实现类似jquery里的animate动画效果

要点一:

startrun(obj,attr,target,fn)

box.onmouseover = function(){
startrun(box,"width",200,function(){
startrun(box,"height",200,function(){
startrun(box,"opacity","100")
});
});
}
如上面,函数也可以做为参数使用,就可以达到先执行某个动作,再执行某个动作的效果了。

 

要点二:

if(cur == target){
clearInterval(obj.timer);
if(fn){
fn();
}
}

当运动到达目标点,关闭定时器,然后就可以执行新的函数了。

 

最后,上代码

<!DOCTYPE html>
<html>
<head>
<meta charset="gb2312" />
<title>无标题文档</title>
<style>
<!--
body{margin:0; padding:0; font:12px/1.5 arial;}
#box{width:100px; height:100px; position:absolute; background:#06c; left:0;filter:alpha(opacity=30); opacity:0.3;}
-->
</style>
<script>
<!--
function getstyle(obj,name){
  if(obj.currentStyle){
      return obj.currentStyle[name];
    }else{
      return getComputedStyle(obj,false)[name];
    }
}

window.onload = function(){
  var box = document.getElementById("box");
    box.onmouseover = function(){
      startrun(box,"width",200,function(){
          startrun(box,"height",200,function(){
              startrun(box,"opacity","100")
            });
        });
    }
    box.onmouseout = function(){
      startrun(box,"height",100,function(){
          startrun(box,"width",100,function(){
              startrun(box,"opacity","30");
            });
        });
    }
}

function startrun(obj,attr,target,fn){
    clearInterval(obj.timer);
    obj.timer = setInterval(function(){
      var cur = 0;
        if(attr == "opacity"){
          cur = Math.round(parseFloat(getstyle(obj,attr))*100);
        }else{
          cur = parseInt(getstyle(obj,attr));
        }
      var speed = (target-cur)/8;
        speed = speed>0?Math.ceil(speed):Math.floor(speed);
        
        if(cur == target){
          clearInterval(obj.timer);
            if(fn){
              fn();
            }
        }else{
          if(attr == "opacity"){
                obj.style.filter = "alpha(opacity="+(cur+speed)+")";
              obj.style.opacity = (cur+speed)/100;
            }else{
            obj.style[attr] = cur + speed + "px";
            }
        }
        
    },30)
}
//-->
</script>
</head>

<body>
<div id="box">
</div>
</body>
</html>













                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值