DIV CSS 佈局教程網

用 JavaScript 做出層的滑動展開與收合效果
編輯:關於JavaScript     

「滑動展開」的視覺關鍵是:不要直接改 display,而是逐格改變高度。以下兩個版本 respectively 用遞迴 setTimeout 與 setInterval 實作,並說明為什麼要對同一個元素重複設定 height。

版本一:遞迴 setTimeout

<script type="text/javascript">
var act;

// 展開:h 逐格增加,直到達到 nMax
function over(s, nMax) {
  var obj = document.getElementById(s);
  var h = parseInt(obj.offsetHeight);

  if (h < nMax) {
    obj.style.height = (h + 2) + "px";
    clearTimeout(act);
    act = setTimeout("over('" + s + "'," + nMax + ")", 10);
  }
}

// 收合:h 逐格減少,直到降到 nMin
function out(s, nMin) {
  var obj = document.getElementById(s);
  var h = parseInt(obj.offsetHeight);

  if (h > nMin) {
    obj.style.height = (h - 2) + "px";
    clearTimeout(act);
    act = setTimeout("out('" + s + "'," + nMin + ")", 10);
  }
}
</script>

<div id="mytd" style="background:#eee; overflow:hidden;">
  滑動展開/收合示範
</div>

用法的關鍵是呼叫時傳入目標高度:over('mytd', 100) 展開到 100px,out('mytd', 0) 收回到 0。

clearTimeout(act) 是為了處理「動畫進行中又被打斷」的情況——若使用者快速反覆滑過,前一次的計時器必須先取消,否則兩條動畫會互相打架。

版本二:setInterval(社群優化版)

<script type="text/javascript">
var intervalId = null;

function move(id, state) {
  var obj = document.getElementById(id);

  if (intervalId != null) window.clearInterval(intervalId);

  function change() {
    var h = parseInt(obj.offsetHeight);
    obj.style.height = (state == "down") ? (h + 2) : (h - 2);
  }

  intervalId = window.setInterval(change, 10);
}
</script>

<table border="1" cellpadding="0" cellspacing="0" id="mytd">
  <tr><td>滑動展開/收合</td></tr>
</table>

這個版本把「往哪個方向」抽成 state 參數,並用 clearInterval 處理打斷,比版本一乾淨。但它有個缺點:沒有停止條件,展開會一路長到無限大。實務上要加上邊界判斷。

修正後的完整版本

function slide(id, targetHeight, duration) {
  var obj = document.getElementById(id);
  var start = parseInt(obj.style.height) || 0;
  var change = targetHeight - start;
  var startTime = 0;

  obj.style.overflow = "hidden";

  function tick(timestamp) {
    if (!startTime) startTime = timestamp;
    var progress = Math.min((timestamp - startTime) / duration, 1);
    obj.style.height = (start + change * progress) + "px";
    if (progress < 1) requestAnimationFrame(tick);
    else obj.style.height = targetHeight + "px";
  }

  requestAnimationFrame(tick);
}

用 requestAnimationFrame 取代 setTimeout 有三個好處:它與螢幕刷新同步(不會撕裂)、在分頁背景時自動暫停(不浪費資源)、時間參數讓你能做真正的 easing 而非等速。

四個關鍵細節

一定要設 overflow: hidden。否則內容會在容器變矮時溢出來,看起來像被裁掉一半的文字浮在外面。這是自作滑動動畫最常見的疏漏。

不要用字串形式的 setTimeout。setTimeout("over('mytd',100)", 10) 等同一次 eval,應改成 setTimeout(function(){ over(s, nMax); }, 10),效率與可讀性都更好。

padding 與 border 會干擾計算。IE 的 offsetHeight 含 padding 與 border,但 style.height 在 content-box 模型下不含。若元素有內距,會出現尺寸跳動。加上 box-sizing: border-box 可以統一計算基準。

其實 CSS 就能做到。上面這一切在現代 CSS 裡只需要兩行:

.panel { max-height: 0; overflow: hidden;
         transition: max-height .3s ease; }
.panel.open { max-height: 500px; }        /* 或用 grid-template-rows: 0fr / 1fr */

用 grid-template-rows: 0fr 切換到 1fr 甚至不必猜高度,是目前的推薦做法。JavaScript 只需要負責切 class:

el.classList.toggle("open");

把動畫交給 CSS(由合成器執行、效能更好、自動尊重 prefers-reduced-motion),JavaScript 只管狀態——這是現代前端的基本分工。

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