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);
}
<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>
.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 版本雖較繁瑣但控制力完全。