完整可運行代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
.detail { display: none; margin-top: 5px; padding: 10px; background: #f5f5f5; border-radius: 4px; }
.toggle-btn { cursor: pointer; color: #0066cc; text-decoration: underline; }
.toggle-btn:hover { color: #cc0000; }
</style>
</head>
<body>
<a href="javascript:void(0)" class="toggle-btn" onclick="toggle('detail1', this)">展開內容 1</a>
<div id="detail1" class="detail">這是第一段詳細內容...</div>
<a href="javascript:void(0)" class="toggle-btn" onclick="toggle('detail2', this)">展開內容 2</a>
<div id="detail2" class="detail">這是第二段詳細內容...</div>
<script>
function toggle(id, btn) {
var el = document.getElementById(id);
if (el.style.display === 'none') {
el.style.display = 'block';
btn.textContent = '收起 ' + btn.textContent.replace('展開', '');
} else {
el.style.display = 'none';
btn.textContent = btn.textContent.replace('收起', '展開');
}
}
</script>
</body>
</html>
核心邏輯
- 使用
display: none/block 控制顯隱。
- 按鈕文本動態切換「展開/收起」。
- 無需 jQuery,原生 JS 體積極小,兼容所有瀏覽器。
進階增強
- 添加 CSS Transition 實現滑動動畫:
.detail { max-height: 0; overflow: hidden; transition: max-height 0.3s; } 配合 JS 設置 max-height: scrollHeight。
- 使用
<details><summary> 原生標簽(HTML5.1),零 JS 實現同樣效果。