註冊/設定頁面常見「必填欄位常駐、選填欄位預設隱藏,點擊『詳細資訊』展開」的互動。本文示範最精簡的原生 JS 實作,並提供現代化改良版本。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>顯示/隱藏 Demo</title>
</head>
<body>
<form>
<label>帳號:<input type="text" required></label><br><br>
<label>密碼:<input type="password" required></label><br><br>
<div id="optionalFields" style="display:none; margin-top:1rem; padding:1rem; border:1px dashed #ccc; border-radius:4px;">
<label>暱稱:<input type="text"></label><br><br>
<label>生日:<input type="date"></label><br><br>
<label>簡介:<textarea rows="3"></textarea></label>
</div>
<button type="button" id="toggleBtn">顯示詳細資訊</button>
</form>
<script>
const box = document.getElementById('optionalFields');
const btn = document.getElementById('toggleBtn');
btn.addEventListener('click', function () {
const isHidden = box.style.display === 'none';
box.style.display = isHidden ? 'block' : 'none';
btn.textContent = isHidden ? '隱藏詳細資訊' : '顯示詳細資訊';
});
</script>
</body>
</html>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(function () {
const $box = $('#optionalFields');
$('#toggleBtn').on('click', function () {
$box.slideToggle(300, function () {
// 動畫結束後更新按鈕文字
$(this).is(':visible')
? $('#toggleBtn').text('隱藏詳細資訊')
: $('#toggleBtn').text('顯示詳細資訊');
});
});
});
</script>
<style>
.collapsible {
overflow: hidden;
max-height: 0;
opacity: 0;
transition: max-height .4s ease, opacity .3s ease;
}
.collapsible.open {
max-height: 500px; /* 足夠大 */
opacity: 1;
}
</style>
<div id="optionalFields" class="collapsible">...</div>
<script>
const box = document.getElementById('optionalFields');
const btn = document.getElementById('toggleBtn');
btn.addEventListener('click', () => {
box.classList.toggle('open');
btn.textContent = box.classList.contains('open') ? '隱藏詳細資訊' : '顯示詳細資訊';
});
</script>
| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
內嵌 onclick + style.display | 零依賴、極簡 | 無動畫、結構行為混雜 | 極簡原型、舊專案維護 |
jQuery slideToggle | 語法簡潔、內建動畫 | 需額外載入 jQuery (30KB+) | 已使用 jQuery 的專案 |
CSS max-height + class 切換 | 零依賴、GPU 加速動畫、關注點分離 | 需估算 max-height 上限 | 現代專案、效能敏感場合 |
aria-expanded="false",切換時同步更新。aria-hidden="true",展開時移除。<button> 自動滿足)。選擇適合專案技術棧的版本,即可輕鬆實現優雅的欄位顯隱切換。