萬盛學電腦網

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

JavaScript 實作 DIV 滑動展開/收縮 (Toggle) 效果完整範例

純 JavaScript 實現無依賴的 DIV 滑動切換效果,支援可配置速度、偏移量、最小/最大高度,展開/收縮文字自動切換。

核心實作

function $(id) { return document.getElementById(id); }

function ToggleDiv() {
  this.toggleId = 'slider';
  this.parentId = 'container';
  this.minHeight = 1;
  this.maxHeight = 200;
  this.speed = 1;
  this.offset = 0.15; // 加速度

  this.load = function() {
    if ($(this.toggleId).style.display === 'none') {
      startToggle('open', this);
    } else {
      startToggle('close', this);
    }
  };
}

function startToggle(method, cfg) {
  var el = $(cfg.toggleId), parent = $(cfg.parentId);
  var addspeed = cfg.speed + cfg.offset;

  if (method === 'open') {
    var openFn = function() {
      var h = el.offsetHeight || 1;
      var nh = h + addspeed;
      addspeed += cfg.offset; // 漸進加速
      if (nh < cfg.maxHeight) {
        el.style.height = nh + 'px';
        el.style.display = 'block';
      } else {
        el.style.height = cfg.maxHeight + 'px';
        el.style.display = 'block';
        parent.innerHTML = '收縮';
        clearInterval(openTimer);
      }
    };
    var openTimer = setInterval(openFn, 100);
  } else { // close
    var closeFn = function() {
      var h = el.offsetHeight;
      var nh = h - addspeed;
      addspeed += cfg.offset;
      if (nh > cfg.minHeight) {
        el.style.height = nh + 'px';
        el.style.display = 'block';
      } else {
        el.style.display = 'none';
        el.style.height = '1px';
        parent.innerHTML = '展開';
        clearInterval(closeTimer);
      }
    };
    var closeTimer = setInterval(closeFn, 100);
  }
}

function doToggle(toggleId, parentId) {
  var t = new ToggleDiv();
  t.toggleId = toggleId;
  t.parentId = parentId;
  t.minHeight = 5;
  t.maxHeight = 110;
  t.speed = 10;
  t.offset = 3;
  t.load();
}

HTML 使用範例

<div style="border:1px dashed blue;width:200px;">
  <h2 id="container" onclick="doToggle('slider', this.id)"
      onmouseover="this.style.cursor='pointer'">展開</h2>
  <div id="slider" style="display:none;overflow:hidden;">
    伸縮效果<br/>伸縮效果<br/>伸縮效果<br/>伸縮效果<br/>伸縮效果<br/>
  </div>
</div>

關鍵技術細節與避坑指南

問題原因解決
display:none 時 offsetHeight=0元素未渲染無幾何資訊展開初期以 1px 起始,或預先 visibility:hidden+position:absolute 測量
style.height 是字串 "100px"需 parseInt 轉數值運算統一用 offsetHeight 讀取數值,寫入時加 'px'
setTimeout 0 延遲執行順序JS 單執行緒,同步代碼優先setTimeout(fn,0) 將 fn 推入宏任務佇列,當前堆疊清空後執行
setInterval 累積誤差定時器不保證精確間隔改用 requestAnimationFrame 或 記錄開始時間計算進度

現代化改寫:CSS Transition + Class 切換

.slider {
  overflow: hidden;
  transition: height 0.3s ease-out;
  height: 0;
}
.slider.open { height: 200px; /* 或 max-height: 500px */ }

// JS 僅切換 class
function toggleSlider(id) {
  var el = document.getElementById(id);
  el.classList.toggle('open');
  // 同步按鈕文字
  document.getElementById('container').textContent = el.classList.contains('open') ? '收縮' : '展開';
}
  • GPU 加速、無 JS 計時器、程式碼極簡
  • max-height 技巧支援不固定高度內容
  • 配合 prefers-reduced-motion 尊重使用者動畫偏好
copyright © 萬盛學電腦網 all rights reserved