DIV CSS 佈局教程網

JS 簡單版動畫彈出層:從零開始的展開與收合
編輯:關於JavaScript     

本文實作一個精簡的動畫彈出層:點擊標題列,內容層以「先快後慢」的方式展開;再點一次則分兩段收合。相較於完整的元件化版本,這份程式把焦點放在「動畫怎麼算」這件事上。

樣式

.list, .listShow {
  position:relative; margin:10px; height:30px; width:100px;
  border:1px solid #ccc; cursor:pointer;
}
.list     { background:#eee; }
.listShow { background:#eff; border-color:#ddd; }

.comment {
  display:none; position:absolute; left:0;
  border:1px solid #ccc; background:#fee;
  width:200px; height:200px; overflow:hidden; z-index:100;
}

JavaScript

var zindex = 0;
function $id(id) { return document.getElementById(id); }

var Bind = function(object, fun) {
  var args = Array.prototype.slice.call(arguments).slice(2);
  return function() { return fun.apply(object, args); };
};

function addEventHandler(oTarget, sEventType, fnHandler) {
  if (oTarget.addEventListener) {
    oTarget.addEventListener(sEventType, fnHandler, false);
  } else if (oTarget.attachEvent) {
    oTarget.attachEvent('on' + sEventType, fnHandler);
  } else {
    oTarget['on' + sEventType] = fnHandler;
  }
}

var Shower = function() {
  this.list = null; this.comment = null;
  this.moveLeft = 80; this.moveTop = 20;
  this.height = 150; this.width = 250;
  this.time = 800;

  this.init = function(lisObj, comObj) {
    this.list = lisObj;
    this.comment = comObj;
    this._fnMove = Bind(this, this.move);
    addEventHandler(this.list, "click", this._fnMove);
  };

  this.move = function() {
    var _this = this;
    var w = 0, h = 0, height = 0, width = 0;
    var startTime = new Date().getTime();

    if (!_this.comment.style.display || _this.comment.style.display == "none") {
      _this.comment.style.display = "block";
      _this.comment.style.height = "0px";
      _this.comment.style.width  = "0px";
      _this.list.style.zIndex = ++zindex;
      _this.list.className = "listShow";

      var comment = _this.comment.innerHTML;
      _this.comment.innerHTML = "";

      var timer = setInterval(function() {
        var timestamp = new Date().getTime() - startTime;
        // easeOutCubic:起始快、結尾慢
        var change = Math.pow((timestamp / _this.time - 1), 3) + 1;

        w = _this.moveLeft * change;
        h = _this.moveTop  * change;
        height = _this.height * change;
        width  = _this.width  * change;

        _this.comment.style.left   = Math.ceil(w) + "px";
        _this.comment.style.top    = Math.ceil(h) + "px";
        _this.comment.style.height = height + "px";
        _this.comment.style.width  = width  + "px";

        if (w > _this.moveLeft) {
          clearInterval(timer);
          _this.comment.style.left   = _this.moveLeft + "px";
          _this.comment.style.top    = _this.moveTop  + "px";
          _this.comment.style.height = _this.height + "px";
          _this.comment.style.width  = _this.width  + "px";
          _this.comment.innerHTML = comment;
        }
      }, 1);
    } else {
      _this.hidden();
    }
  };

  this.hidden = function() {
    var _this = this, flag = 1;
    var hiddenTimer = setInterval(function() {
      if (flag == 1) {
        // 第一段:縮高度
        _this.comment.style.height = parseInt(_this.comment.style.height) - 10 + "px";
      } else {
        // 第二段:縮寬度並同時左移
        _this.comment.style.width = parseInt(_this.comment.style.width) - 15 + "px";
        _this.comment.style.left  = parseInt(_this.comment.style.left) + 5 + "px";
      }
      if (flag == 1 && parseInt(_this.comment.style.height) < 10) flag = -flag;

      if (parseInt(_this.comment.style.width) < 20) {
        clearInterval(hiddenTimer);
        _this.comment.style.left = "0px";
        _this.comment.style.top  = "0px";
        _this.comment.style.height = "0px";
        _this.comment.style.width  = "0px";
        _this.comment.style.display = "none";
        if (_this.list.style.zIndex == zindex) zindex--;
        _this.list.style.zIndex = 0;
        _this.list.className = "list";
      }
    }, 1);
  };
};

window.onload = function() {
  var s1 = new Shower(); s1.init($id("list1"), $id("comment1"));
  var s2 = new Shower(); s2.init($id("list2"), $id("comment2"));
  var s3 = new Shower(); s3.init($id("list3"), $id("comment3"));
};

HTML 只要三組「觸發列 + 內容層」的結構,每個觸發列都帶一個對應的 comment div 即可。

兩個技術重點

用時間而非次數計算進度。因為位移量是 時間比例 的函式,所以不管裝置快慢,動畫的總時長都固定在 800 毫秒左右。若改用「每次加固定值」,在效能不同的裝置上速度就會不一致。

收合用 flag 做兩段式。flag 從 1 翻轉為 -1 的瞬間,就是從「縮高度」切換到「縮寬度+左移」的時機,讓收合看起來像被捲起來,比單純縮放自然。

建議的現代改寫

這份程式很適合成為理解動畫原理的教材,但實際專案請用 CSS:

// 只需要切換 class
el.addEventListener('click', function() {
  this.nextElementSibling.classList.toggle('open');
});
.comment {
  transform: scale(0); transform-origin: top left;
  opacity: 0; transition: transform .35s cubic-bezier(.33,1,.68,1), opacity .35s;
}
.comment.open { transform: scale(1); opacity: 1; }

這樣做的好處是:動畫由瀏覽器的合成器處理,不會阻塞主執行緒; also 更容易被 prefers-reduced-motion 這類使用者偏好設定 respect。

另外提醒,setInterval(fn, 1) 不會真的每毫秒執行一次(瀏覽器有最小間隔限制),寫成 1 只會增加不必要的排程負擔。

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