【问题标题】:jQuery - unbind or rebind hoverIntent()?jQuery - 取消绑定或重新绑定 hoverIntent()?
【发布时间】:2011-11-16 11:57:18
【问题描述】:

我有一个菜单栏,在上面一行显示一组类别。

其中一个类别有一组子类别。

我有一个 hoverIntent 设置,它会在子菜单中向下滑动,并在鼠标离开时向上滑动。

但是,如果我正在查看此类别中的页面,我希望子菜单可见并突出显示活动类别。我还想确保当通过鼠标与子菜单交互时,一旦鼠标离开它就不会再次向上滑动。

我已经尝试在这个页面的元素上重新声明 hoverIntent 函数但是它不起作用,它仍然使用之前的绑定。有什么办法可以解开之前的 hoverIntent 并确保它使用新的?

【问题讨论】:

  • 您可以尝试拥有两个类,并为每个类绑定一个事件。然后你只需要在相关元素上添加/删除正确的类。

标签: jquery unbind hoverintent


【解决方案1】:

绑定和取消绑定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)

【讨论】:

  • 谢谢你!我一直在寻找,只是一个问题.. removeProp "hoverIntent_t" 是做什么的?
【解决方案2】:

我认为这是一个更完整的答案。它执行以下操作:

  • 所有活动的计时器都会被清除。
  • 清除所有事件
  • 所有对象属性都被清除
  • 使用常见的 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);

【讨论】:

【解决方案3】:

来自 jQuery 文档:“在最简单的情况下,没有参数,.unbind() 删除所有附加到元素的处理程序”

【讨论】:

    【解决方案4】:

    我用过:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多