DIV CSS 佈局教程網

九種原生 JavaScript 動畫效果,不靠框架也能寫
編輯:關於JavaScript     

做頁面時動畫幾乎不可避免,但很多人習慣直接抓 jQuery 的 animate。其實用原生 JS 完全可以寫出同等效果,而且理解原理之後,框架的行為也不再是黑盒子。以下九種由淺入深。

1. 勻速動畫

從頭到尾每次移動的固定像素都一樣。實作骨架是:清除舊計時器 → 判斷方向 → 每次位移固定值 → 到達目標停止。

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>勻速動畫</title>
<style type="text/css">
html,body{margin:0;padding:0;}
div{margin:0;padding:0;}
.odiv{width:200px; height:200px; background:#f00; position:relative; left:-200px; top:100px;}
.sdiv{width:20px; height:60px; background:#00f; position:absolute; top:70px; right:-20px;}
</style>
</head>
<body>
<div id="odiv" class="odiv">
  <div id="sdiv" class="sdiv"></div>
</div>
</body>
</html>
<script language="javascript">
window.onload = function(){
  var odiv = document.getElementById('odiv');
  odiv.onmouseover = function(){ startMover(0); }
  odiv.onmouseout  = function(){ startMover(-200); }
}
var timer = null;
function startMover(itarget){
  clearInterval(timer); //執行當前動畫同時清除之前的動畫
  var odiv = document.getElementById('odiv');
  timer = setInterval(function(){
    var speed = 0;
    if(odiv.offsetLeft > itarget){ speed = -1; }
    else{ speed = 1; }
    if(odiv.offsetLeft == itarget){
      clearInterval(timer);
    } else {
      odiv.style.left = odiv.offsetLeft + speed + 'px';
    }
  },30);
}
//offsetWidth  = width + padding + border
//offsetHeight = height + padding + border
//offsetLeft   = offsetParent 的 padding-left + 中間元素的 offsetWidth + 當前元素的 margin-left
//offsetParent 會取「最近的、已定位(absolute/relative)的父元素」,若無則為 body
</script>

兩個一定要記的觀念:動畫前必須 clearInterval,否則快速滑動會堆疊出多個計時器互相打架;offsetLeft 是相對於 offsetParent 的,而 offsetParent 是最近一個設了定位的祖先。

2. 緩衝動畫

速度不再固定,而是依「距離目標的遠近」動態調整:離得遠跑得快,越接近越慢,視覺上就有阻尼感。

 <script language="javascript">
window.onload = function(){
  var odiv = document.getElementById('odiv');
  odiv.onmouseover = function(){ startMover(0); }
  odiv.onmouseout  = function(){ startMover(-200); }
}
var timer = null;
function startMover(itarget){
  clearInterval(timer);
  var odiv = document.getElementById('odiv');
  timer = setInterval(function(){
    var speed = (itarget - odiv.offsetLeft)/10; //緩衝動畫的速度參數變化值
    //速度為正代表向右走,向上取整;反之向下取整
    speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
    if(odiv.offsetLeft == itarget){
      clearInterval(timer);
    } else {
      odiv.style.left = odiv.offsetLeft + speed + 'px';
    }
  },30);
}
</script>

取整是這裡的靈魂。若不取整,速度會變成小數,offsetLeft 永遠等不到剛好等於目標值的那一刻,動畫就會無限跑下去。正數用 ceil、負數用 floor,是為了確保每次都至少移動 1 像素,能真正收斂。

3. 透明度動畫

 <script language="javascript">
window.onload = function(){
  var odiv = document.getElementsByTagName('div');
  for(var i=0;i<odiv.length;i++) {
    odiv[i].onmouseover = function(){ startOP(this,100); }
    odiv[i].onmouseout  = function(){ startOP(this,30); }
    odiv[i].timer = null; //事先定義
    odiv[i].alpha = null; //事先定義
    //動畫屬性可以不預先定義,但透明度屬性必須定義,否則報錯
  }
}
function startOP(obj,utarget){
  clearInterval(obj.timer);
  obj.timer = setInterval(function(){
    var speed = 0;
    if(obj.alpha > utarget){ speed = -10; }
    else{ speed = 10; }
    obj.alpha = obj.alpha + speed;
    if(obj.alpha == utarget){
      clearInterval(obj.timer);
    }
    obj.style.filter = 'alpha(opacity:'+obj.alpha+')'; //基於IE
    obj.style.opacity = parseInt(obj.alpha)/100;
  },30);
}
</script>

透明度要同時寫 opacity 與 IE 的 filter: alpha()。另外,每個元素都要有自己的 timer 與 alpha,不能共用,這是多元素動畫的第一課。

4. 多物體動畫

 <script language="javascript">
window.onload = function(){
  var olist = document.getElementsByTagName('li');
  for(var i=0; i<olist.length;i++) {
    olist[i].onmouseover = function(){ startmov(this,400); };
    olist[i].onmouseleave = function(){ startmov(this,200); };
    olist[i].timer = null;
  }
  function startmov(obj,itarget){
    clearInterval(obj.timer);
    obj.timer = setInterval(function(){
      var speed = 0;
      speed = (itarget - obj.offsetWidth)/8;
      speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
      if(obj.offsetWidth == itarget){
        clearInterval(obj.timer);
      } else {
        obj.style.width = obj.offsetWidth + speed + 'px';
      }
    },30);
  }
}
//offsetWidth 取得的是元素實際寬度(含邊框與內距)
//只要是多物體運動,所有屬性都不能共用
</script>

5. 取得計算後樣式

寫通用動畫時,起點值不能寫死,必須讀出元素目前的實際樣式。IE 用 currentStyle,其餘瀏覽器用 getComputedStyle:

 <script language="javascript">
/* currentStyle:獲取計算後的樣式,可拿到瀏覽器預設值,但無法取復合樣式(如 background)。
   支援:IE、Opera
   getComputedStyle(obj,false):支援 FireFox、Chrome、Safari,第二參數為相容舊版火狐所用。 */
window.onload = function(){
  var odiv = document.getElementById('odiv');
  odiv.onmouseover = function(){ startMov(this); };
  function startMov(obj){
    setInterval(function(){
      obj.style.width = parseInt(getStyle(obj,'width'))+1+'px';
      obj.style.fontSize = parseInt(getStyle(obj,'fontSize'))+1+'px';
    },30);
  }
  function getStyle(obj,attr) {
    if(obj.currentStyle){
      return obj.currentStyle[attr];
    } else {
      return getComputedStyle(obj,false)[attr];
    }
  }
}
</script>

這個 getStyle 封裝是後面所有動畫的基礎元件,幾乎每個動畫庫都有對應實作。

6. 多物體複雜動畫

把要動的屬性當參數傳進來,一個函式就能處理寬、高、透明度等各種需求。

 <script language="javascript">
window.onload = function(){
  var li1 = document.getElementById('li1');
  var li2 = document.getElementById('li2');
  li1.onmouseover = function(){ startMov(this,400,'width'); };
  li1.onmouseout  = function(){ startMov(this,200,'width'); };
  li2.onmouseover = function(){ startMov(this,200,'height'); };
  li2.onmouseout  = function(){ startMov(this,100,'height'); };

  function startMov(obj,itarget,attr){
    clearInterval(obj.timer);
    obj.timer = setInterval(function(){
      var icur = parseInt(getStyle(obj,attr));
      var speed = (itarget - icur)/8;
      speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
      if(icur == itarget){
        clearInterval(obj.timer);
      } else {
        obj.style[attr] = icur + speed + 'px';
      }
    },30);
  }
  function getStyle(obj,attr) {
    if(obj.currentStyle){ return obj.currentStyle[attr]; }
    else{ return getComputedStyle(obj,false)[attr]; }
  }
}
</script>

7. 加上透明度支援

 <script language="javascript">
window.onload = function(){
  var li1 = document.getElementById('li1');
  var li2 = document.getElementById('li2');
  li1.onmouseover = function(){ startMov(this,100,'opacity'); };
  li1.onmouseout  = function(){ startMov(this,30,'opacity'); };
  li2.onmouseover = function(){ startMov(this,200,'height'); };
  li2.onmouseout  = function(){ startMov(this,100,'height'); }
  li1.timer = null;
  li2.timer = null;

  function startMov(obj,itarget,attr){
    clearInterval(obj.timer);
    obj.timer = setInterval(function(){
      var icur = 0;
      if(attr == 'opacity'){
        //轉換成整數並四捨五入,因為電腦算小數往往不準確
        icur = Math.round(parseFloat(getStyle(obj,attr))*100);
      } else {
        icur = parseInt(getStyle(obj,attr));
      }
      var speed = (itarget - icur)/8;
      speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
      if(icur == itarget){
        clearInterval(obj.timer);
      } else {
        if(attr == 'opacity'){
          obj.style.filter = 'alpha(opacity:'+(icur+speed)+')';
          obj.style.opacity = (icur+speed)/100;
        } else {
          obj.style[attr] = icur + speed + 'px';
        }
      }
    },30);
  }
  function getStyle(obj,attr) {
    if(obj.currentStyle){ return obj.currentStyle[attr]; }
    else{ return getComputedStyle(obj,false)[attr]; }
  }
}
</script>

透明度的特殊之處有兩點:讀出來是 0~1 的小數,要乘 100 變整數再運算;浮點運算誤差會讓它永遠等不到整數目標值,所以務必四捨五入。

8. 鏈式動畫

用回呼函式把動畫串起來,前一段完成才啟動下一段。

 <script language="javascript">
window.onload = function(){
  var li1 = document.getElementById('li1');
  li1.onmouseover = function(){
    startMov(li1,400,'width',function(){
      startMov(li1,200,'height',function(){
        startMov(li1,100,'opacity');
      });
    });
  };
  li1.onmouseout = function(){
    startMov(li1,30,'opacity',function(){
      startMov(li1,100,'height',function(){
        startMov(li1,100,'width');
      });
    });
  };
  li1.timer = null;

  function startMov(obj,itarget,attr,fn){//fn回調函數
    clearInterval(obj.timer);
    obj.timer = setInterval(function(){
      var icur = 0;
      if(attr == 'opacity'){
        icur = Math.round(parseFloat(getStyle(obj,attr))*100);
      } else {
        icur = parseInt(getStyle(obj,attr));
      }
      var speed = (itarget - icur)/8;
      speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
      if(icur == itarget){
        clearInterval(obj.timer);
        if(fn){ fn(); }
      } else {
        if(attr == 'opacity'){
          obj.style.filter = 'alpha(opacity:'+(icur+speed)+')';
          obj.style.opacity = (icur+speed)/100;
        } else {
          obj.style[attr] = icur + speed + 'px';
        }
      }
    },30);
  }
  function getStyle(obj,attr) {
    if(obj.currentStyle){ return obj.currentStyle[attr]; }
    else{ return getComputedStyle(obj,false)[attr]; }
  }
}
</script>

9. 多值同時運動(並支援鏈式)

最終形態:傳入一個 JSON 一次動多個屬性,全部到位後再觸發回呼。

 <script language="javascript">
window.onload = function(){
  var li1 = document.getElementById('li1');
  li1.onmouseover = function(){ startMov(li1,{width:201,height:200,opacity:100}); };
  li1.onmouseout  = function(){ startMov(li1,{width:200,height:100,opacity:30}); };
  li1.timer = null;

  function startMov(obj,json,fn){//fn回調函數
    clearInterval(obj.timer);
    var flag = true; //是否動畫都完成了
    obj.timer = setInterval(function(){
      for(var attr in json){
        var icur = 0;
        if(attr == 'opacity'){
          icur = Math.round(parseFloat(getStyle(obj,attr))*100);
        } else {
          icur = parseInt(getStyle(obj,attr));
        }
        var speed = (json[attr] - icur)/8;
        speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
        if(icur != json[attr]){ flag = false; }
        if(attr == 'opacity'){
          obj.style.filter = 'alpha(opacity:'+(icur+speed)+')';
          obj.style.opacity = (icur+speed)/100;
        } else {
          obj.style[attr] = icur + speed + 'px';
        }
        if(flag){
          clearInterval(obj.timer);
          if(fn){ fn(); }
        }
      }
    },30);
  }
  function getStyle(obj,attr) {
    if(obj.currentStyle){ return obj.currentStyle[attr]; }
    else{ return getComputedStyle(obj,false)[attr]; }
  }
}
</script>

這個版本已經具備了迷你動畫庫的雛形。仔細看會發現 flag 的判斷放在 for 迴圈內部,這其實是個瑕疵——應該在迴圈跑完所有屬性之後再統一判斷,否則多屬性時可能提前結束。這也說明了為什麼自己寫動畫能學到東西:你會親手碰到這些細節。

九種效果各自的重點:勻速看 offsetLeft 與計時器管理、緩衝看取整收斂、透明度看跨瀏覽器寫法、多物體看屬性隔離、樣式讀取看 getStyle 封裝、複雜動畫看參數化、鏈式看回呼、最終版看 JSON 驅動。把它們串起來,就是一個動畫引擎的完整脈絡。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved