2011-11-16 58 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;