javascript實現animate()動畫效果程式碼例項

admin發表於2017-04-05

本章節分享一段程式碼例項,它實現了jQuery中的animate()動畫出效果。通過此程式碼,也可以基本瞭解一下jQuery是如何實現動畫效果的,需要的朋友可以做一下參考。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<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>

相關文章