綁定 mouseenter 與 mouseleave 的語法糖,自動處理冒泡問題。
$('#panel h5.head').hover(
function() { $(this).next().show(); }, // 進入
function() { $(this).next().hide(); } // 離開
);
注意:jQuery 1.9 移除 .toggle(fn, fn)(點擊切換函數),僅保留 .toggle()(顯示/隱藏切換)。若需點擊切換邏輯,請自行實現:
// 手動實現點擊切換邏輯
var toggled = false;
$('#panel h5.head').click(function() {
toggled = !toggled;
if (toggled) {
$(this).next().show();
$(this).addClass('highlight');
} else {
$(this).next().hide();
$(this).removeClass('highlight');
}
});
// 等價於 if(visible) hide() else show()
$('#panel h5.head').click(function() {
$(this).next().toggle();
});
.highlight { background: #FF3300; }
$('#panel h5.head').click(function() {
$(this).toggleClass('highlight');
$(this).next().slideToggle(200); // 滑動切換
});
| 事件 | 冒泡 | 子元素觸發 | 適用場景 |
|---|---|---|---|
hover (內部用 mouseenter/leave) | 否 | 否 | 菜單、Tooltip、卡片懸停 |
mouseover/out | 是 | 是 | 需追蹤進出子元素的複雜邏輯 |
// CSS :hover 側重樣式
.card:hover .dropdown { display: block; }
// JS 互動邏輯:使用 mouseenter/leave
element.addEventListener('mouseenter', show);
element.addEventListener('mouseleave', hide);
// 點擊切換:狀態機模式
let open = false;
trigger.addEventListener('click', () => {
open = !open;
panel.hidden = !open;
trigger.classList.toggle('active', open);
});
hover() 是處理懸停交互的最佳 jQuery 選擇;toggle(fn,fn) 已棄用,請改用狀態變數手動控制。現代開發優先用 CSS :hover 處理純樣式變化,JS 僅處理狀態切換與複雜邏輯。