純 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();
}
<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 或 記錄開始時間計算進度 |
.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') ? '收縮' : '展開';
}
max-height 技巧支援不固定高度內容prefers-reduced-motion 尊重使用者動畫偏好