jQuery 把兩組常見的成對事件效果包裝成了單一方法:hover 處理「移入與移出」,toggle 處理「反覆點擊」。理解它們各自的行為,能省下不少重複程式碼。
hover 模擬懸停事件,接受兩個函式:第一個在滑鼠移入時觸發,第二個在移出時觸發。它是一個「保持在其中」狀態的語法糖,省去分別綁定 mouseover 與 mouseout。
<script type="text/javascript">
$(function () {
$("#panel h5.head").hover(
function () { $(this).next().show(); }, // 滑鼠懸浮時顯示
function () { $(this).next().hide(); } // 滑鼠離開時隱藏
);
});
</script>
注意這裡的 $(this).next():它取得目前元素的「下一個兄弟元素」,因此不必為每個面板寫死 id,同一段程式碼能套用到多組元素上。這是 jQuery 相對位移選擇器的典型用法。
toggle 接受兩個函式:第一次點擊觸發第一個,第二次觸發第二個,之後不斷輪替。若中途想解除,可用 unbind("click")。
<script type="text/javascript">
$(function () {
$("#panel h5.head").toggle(
function () { $(this).next().show(); }, // 第一次點擊
function () { $(this).next().hide(); } // 第二次之後輪流切換
);
});
</script>
這裡必須特別注意:toggle 在 jQuery 中有兩種完全不同的行為。
帶函式參數時,是上述的「點擊輪替處理器」。
不帶參數時,它單純切換元素的可見狀態——目前可見就隱藏,目前隱藏就顯示。
因此上面的程式碼可以簡化為:
<script type="text/javascript">
$(function () {
$("#panel h5.head").toggle(
function () { $(this).next().toggle(); },
function () { $(this).next().toggle(); }
);
});
/* 甚至可以直接寫成
$(function () {
$("#panel h5.head").click(function () { $(this).next().toggle(); });
}) */
</script>
這個重載造成的混淆相当有名,而且帶函式參數的 toggle 已在 jQuery 1.9 中被移除。若你在維護舊專案看到它,記得它現在需要自己實作。
<style type="text/css">
.highlight { background: #FF3300; }
</style>
<script type="text/javascript">
$(function () {
$("#panel h5.head").toggle(
function () { // 配合 css 樣式使用
$(this).addClass("highlight");
$(this).next().show();
},
function () {
$(this).removeClass("highlight");
$(this).next().hide();
}
);
});
</script>
用 addClass 而非直接改 style,能把視覺決定權留在 CSS 中,設計師改配色時不必動 JavaScript。
hover 至今仍然好用且無替代品疑慮。但 toggle 的點擊輪替版本已被移除,建議改用狀態旗標或 class 判斷:
$("#panel h5.head").on('click', function () {
var $panel = $(this).next();
$panel.toggleClass('open'); // 用 class 控制顯示
$(this).toggleClass('highlight');
});
搭配 CSS:
.panel { display: none; }
.panel.open { display: block; }
用 class 表達狀態的好處是:狀態變成可查詢的(hasClass('open')),也能被 CSS 樣式、其他程式碼共用,不必再維護一個你自己記得的布林變數。