內容區塊的展開與收合是常見 UI 互動模式。本文詳細解析如何使用原生 JavaScript 結合 CSS,實現無依賴、高效能的平滑滑動動畫,適合 FAQ 列表、側邊選單、內容摺疊等場景。
利用 setInterval 定時器漸進式修改元素 height 屬性,配合 overflow: hidden 實現視覺上的滑動效果。關鍵在於計算目標高度、控制動畫速度與幀率。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>很酷的 DIV 層展開收縮效果</title>
<style>
* { margin:0; padding:0; }
body { text-align:center; font:75% Verdana, Arial, Helvetica, sans-serif; }
h1 {
font:125% Arial, Helvetica, sans-serif;
text-align:left;
font-weight:bolder;
background:#333;
padding:3px;
display:block;
color:#99CC00
}
.class1 {
width:40%;
background:#CCC;
position:relative;
margin:0 auto;
padding:5px;
}
span {
position:absolute;
right:10px;
top:8px;
cursor:pointer;
color:yellow;
}
p {
text-align:left;
line-height:20px;
background:#333;
padding:3px;
margin-top:5px;
color:#99CC00
}
#class1content {
height:300px;
overflow:hidden;
display:none;
}
</style>
<script>
// 簡易選取器
function $(element) {
return document.getElementById(element);
}
// 展開動畫
function $D() {
var d = $('class1content');
var h = d.offsetHeight;
var maxh = 300;
function dmove() {
h += 50; // 展開速度
if (h >= maxh) {
d.style.height = '300px';
clearInterval(iIntervalId);
} else {
d.style.display = 'block';
d.style.height = h + 'px';
}
}
iIntervalId = setInterval(dmove, 2);
}
// 收合動畫
function $D2() {
var d = $('class1content');
var h = d.offsetHeight;
var maxh = 300;
function dmove() {
h -= 50; // 收合速度
if (h <= 0) {
d.style.display = 'none';
clearInterval(iIntervalId);
} else {
d.style.height = h + 'px';
}
}
iIntervalId = setInterval(dmove, 2);
}
// 切換邏輯
function $use() {
var d = $('class1content');
var sb = $('stateBut');
if (d.style.display === 'none') {
$D();
sb.innerHTML = '收縮';
} else {
$D2();
sb.innerHTML = '展開';
}
}
</script>
</head>
<body>
<div class="class1">
<h1>DIV層的展開隱藏效果</h1>
<span id="stateBut" onclick="$use()">展開</span>
<p id="class1content">
曾經有一份真誠的愛情放在我面前,<br>
我沒有珍惜,<br>
等我失去的時候我才後悔莫及,<br>
人世間最痛苦的事莫過於此。<br>
如果上天能夠給我一個再來一次的機會,<br>
我會對那個女孩子說三個字:<br>
我愛你。<br>
如果非要在這份愛上加上一個期限,<br>
我希望是……一萬年!
</p>
</div>
</body>
</html>
setInterval 控制幀率(2ms/幀 ≈ 500fps,實際受瀏覽器限制約 60fps)display: none 與 display: block 切換配合高度動畫,避免佔據版面空間overflow: hidden 確保內容在高度縮小時不外溢現代瀏覽器完整支援 CSS Transition,可大幅簡化程式碼並提升效能:
<style>
.panel {
max-height: 0;
overflow: hidden;
transition: max-height 0.4s ease-out;
}
.panel.open {
max-height: 500px; /* 需設定足夠大的最大高度 */
}
</style>
<script>
document.querySelector('.trigger').addEventListener('click', function() {
var panel = document.querySelector('.panel');
panel.classList.toggle('open');
this.textContent = panel.classList.contains('open') ? '收合' : '展開';
});
</script>
scrollHeight 獲取內容真實高度,避免硬編碼 max-heighttransitionend 事件執行後續邏輯aria-expanded、aria-controls、鍵盤操作支援translateY) 而非 height 動畫,避免觸發重排requestAnimationFrame 替代 setInterval 實現更平滑的 JS 動畫will-change: height 或 transform: translateZ(0)