萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery hover() 與 toggle() 方法深度解析與實戰模式

hover(handlerIn, handlerOut)

綁定 mouseenter 與 mouseleave 的語法糖,自動處理冒泡問題。

$('#panel h5.head').hover(
    function() { $(this).next().show(); },   // 進入
    function() { $(this).next().hide(); }    // 離開
);

toggle(fn1, fn2, ...)

注意: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');
    }
});

.toggle():顯示/隱藏切換

// 等價於 if(visible) hide() else show()
$('#panel h5.head').click(function() {
    $(this).next().toggle();
});

進階模式:配合 CSS 類別

.highlight { background: #FF3300; }

$('#panel h5.head').click(function() {
    $(this).toggleClass('highlight');
    $(this).next().slideToggle(200); // 滑動切換
});

hover vs mouseover/mouseout

事件冒泡子元素觸發適用場景
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 僅處理狀態切換與複雜邏輯。

copyright © 萬盛學電腦網 all rights reserved