FAQ 頁面、側邊欄分類、設定面板,都會用到「點標題收合內容」的交互。用 jQuery 實作,核心其實只有 toggle() 搭配 animate() 兩行。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>jQuery 實現 DIV 層的收縮展開效果</title>
<script type="text/javascript" src="/images/jquery.js"></script>
<style>
.text{line-height:22px;padding:0 6px;color:#666;}
.box h1{padding-left:10px;height:22px;line-height:22px;background:#f1f1f1;font-weight:bold;}
.box{position:relative;border:1px solid #e7e7e7;}
</style>
</head>
<body>
<script type="text/javascript">
$(document).ready(function(){
$(".box h1").toggle(function(){
$(this).next(".text").animate({height: 'toggle', opacity: 'toggle'}, "slow");
}, function(){
$(this).next(".text").animate({height: 'toggle', opacity: 'toggle'}, "slow");
});
});
</script>
<div class="box">
<h1>收縮展開效果</h1>
<div class="text">
1<br />2<br />3<br />4<br />5<br />
</div>
</div>
<br />
<div class="box">
<h1>收縮展開效果</h1>
<div class="text">
1<br />2<br />
</div>
</div>
<br>
<font color=red>第一次運行請刷新一下頁面。</font>
</body>
</html>
1. next(".text") 的相對定位思路。不要寫死 id,而是從被點擊的 h1 出發,找它「下一個同層的 .text」。這樣同一頁放幾組 box 都不用改程式,這是可重複使用元件的基本寫法。
2. height: 'toggle' 與 opacity: 'toggle'。toggle 是 animate 的特殊值,意思是「目前可見就收到 0,目前隱藏就展開到原本的高度」,不必 ourselves 去判斷狀態。加上 opacity 讓收合過程帶一點淡出,視覺更柔和。
3. toggle(fn, fn) 的意義。這個形式的 toggle 會把兩個函式輪流觸發:第一次點擊跑第一個,第二次跑第二個,之後往復。範例中兩個函式內容相同,是因為 animate 的 toggle 值本身就能處理方向;如果要做「展開時改箭頭、收合時改回來」,就分別寫進兩個回呼裡。
cursor:pointer,並在 h1 右側放一個箭頭字元,收合時旋轉 180 度。.text 全部 slideUp()。.children() 精準往下找一層,避免誤傷巢狀內容。第一次執行時如遇版面異常,重新整理一次即可。