萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 實現 DIV 緩慢展開/收合動畫(手寫滑動引擎)

效果特色

  • 點擊標題列觸發面板緩慢展開/收合
  • 高度、步長、幀間隔可配置(mh, step, ms)
  • 不受內容高度限制,自動偵測 offsetHeight 作為最大高度
  • 多面板獨立運作,互不干擾

核心引擎

var mh = 30;      // 最小高度(收合狀態)
var step = 1;     // 每幀變化量(px)
var ms = 10;      // 幀間隔(ms)

function toggle(o) {
  if (!o.tid) o.tid = '_' + Math.random() * 100;
  if (!window.toggler) window.toggler = {};
  if (!window.toggler[o.tid]) {
    window.toggler[o.tid] = {
      obj: o,
      maxHeight: o.offsetHeight,
      minHeight: mh,
      timer: null,
      action: 1  // 1=展開, -1=收合
    };
  }
  o.style.height = o.offsetHeight + 'px'; // 固定高度啟用動畫
  if (window.toggler[o.tid].timer) clearTimeout(window.toggler[o.tid].timer);
  window.toggler[o.tid].action *= -1; // 切換方向
  window.toggler[o.tid].timer = setTimeout('anim("' + o.tid + '")', ms);
}

function anim(id) {
  var t = window.toggler[id], o = t.obj;
  if (t.action < 0) { if (o.offsetHeight <= t.minHeight) { clearTimeout(t.timer); return; } }
  else { if (o.offsetHeight >= t.maxHeight) { clearTimeout(t.timer); return; } }
  o.style.height = (parseInt(o.style.height) + t.action * step) + 'px';
  t.timer = setTimeout('anim("' + id + '")', ms);
}

HTML 結構

<div class="xx">
  <h5 onclick="toggle(this.parentNode)">點擊此處層伸縮</h5>
  <p>內容內容內容...</p>
</div>

<style>
.xx { border:1px solid; overflow:hidden; }
.xx h5 { border-bottom:1px solid; padding:0; margin:0; height:28px; line-height:30px; cursor:pointer; background:#eee; }
</style>

現代化替代:CSS Transition

.panel { overflow:hidden; transition: height 0.3s ease; }
.panel.collapsed { height: 30px; } /* 最小高度 */
.panel:not(.collapsed) { height: auto; } /* 需配合 JS 設定具體 px 值或使用 max-height 技巧 */

配合 max-height: 0 → 9999px 過渡可實現純 CSS 高度動畫,但無法精確控制最終高度;JS 版本雖較繁瑣但控制力完全。

copyright © 萬盛學電腦網 all rights reserved