2011-11-16 53 views
9

我有一個菜單欄,在上面一行顯示一組類別。jQuery - 取消綁定或重新綁定hoverIntent()?

其中一個類別有一組子類別。

我有一個hoverIntent設置,這樣它將slideDown子菜單,並在鼠標離開時滑動。

但是,如果我正在查看此類別的頁面,我希望子菜單在高亮顯示的活動類別中可見。我還想確保當子菜單通過鼠標進行交互時,鼠標離開後它不會再次滑動。

我已經嘗試在此頁面的元素上重新聲明hoverIntent函數,但它不起作用,它仍然使用上一個綁定。有什麼方法可以解除之前的hoverIntent並確保它使用新的?

+0

你可以嘗試有兩個類,並將一個事件綁定到每個事件。然後,您只需添加/刪除相關元素上的正確類。 – Jerome

回答

19

綁定和取消綁定hoverIntent你應該做的:

// bind the hoverIntent 
$("#demo1 li").hoverIntent(makeTall, makeShort) 
// unbind the hoverIntent 
$("#demo1 li").unbind("mouseenter").unbind("mouseleave"); 
$("#demo1 li").removeProp('hoverIntent_t'); 
$("#demo1 li").removeProp('hoverIntent_s'); 
// rebind the hoverIntent 
$("#demo1 li").hoverIntent(makeTall, makeShort) 
+0

完美,謝謝! – waffl

+0

謝謝你!我正在尋找,只是一個問題..什麼是removeProp「hoverIntent_t」使? –

1

從jQuery的文檔:「在最簡單的情況下,不帶任何參數,.unbind()將附着元素的所有處理」

10

我認爲這是一個更完整的答案。它執行以下操作:

  • 任何活動計時器都將被清除。
  • 所有事件都被清除
  • 所有對象的屬性將被清除
  • 採用常見的jQuery的語法和看起來像hoverIntent

代碼的本地部分:

(function($) { 
    if (typeof $.fn.hoverIntent === 'undefined') 
    return; 

    var rawIntent = $.fn.hoverIntent; 

    $.fn.hoverIntent = function(handlerIn,handlerOut,selector) 
    { 
     // If called with empty parameter list, disable hoverintent. 
     if (typeof handlerIn === 'undefined') 
     { 
     // Destroy the time if it is present. 
     if (typeof this.hoverIntent_t !== 'undefined') 
     { 
      this.hoverIntent_t = clearTimeout(this.hoverIntent_t); 
     } 
     // Cleanup all hoverIntent properties on the object. 
     delete this.hoverIntent_t; 
     delete this.hoverIntent_s; 

     // Unbind all of the hoverIntent event handlers. 
     this.off('mousemove.hoverIntent,mouseenter.hoverIntent,mouseleave.hoverIntent'); 

     return this; 
     } 

     return rawIntent.apply(this, arguments); 
    }; 
})(jQuery); 
+1

我不得不在'this.each'調用中包裝函數的內容,以便能夠在集合上調用它:https://gist.github.com/raulferras/10458877 –

+0

很好地完成了。我已經開始了一個github請求來獲得一個添加到源代碼中的解除綁定/銷燬方法,因爲這看起來像是與良好的插件行爲一致的東西:https://github.com/briancherne/jquery-hoverIntent/issues/43 – tohster

0

我用:

var elements = $("#main_nav li, #breadcrumb_ul li"); 
elements.unbind('mouseover mouseout'); 
delete $(elements).hoverIntent_t; 
delete $(elements).hoverIntent_s;