当子元素上的hoverIntent触发时,如何取消父元素上的hoverIntent?

时间:2011-05-25 18:55:58

标签: jquery hoverintent

我有一个父元素,当盘旋时显示一个元素。我还有一个子元素,当盘旋时显示不同的元素。

我不希望他们两个同时开火 - 也就是说,如果你在孩子上面盘旋,我只想显示它的相关元素 - 并抑制悬停在父元素上。

我无法让它可靠地工作。可能遗漏了一些明显的东西。有什么想法吗?

修改 - 澄清:

在这种情况下,“父”和“子”是彼此不了解的独立可重用组件,因此我实际上无法将上下文从一个注入到另一个中

以下是我使用jQuery& amp; hoverIntent插件。

HTML:

<div id="parentBar">
    <ul id="childMenu">
        <li>Menu 1</li>
    </ul>
</div>

<div id="barInfo">
    <p>This is shown when hovering overing inside of the parent bar.</p>
</div>

<div id="menuInfo">
    <p>This is shown when hovering over inside of the child menu.</p>
</div>

CSS:

#parentBar{width:500px;border:solid 1px black;}
#childMenu{margin-left:10px;padding-left:10px;width:100px;border:solid 1px green;}
#menuInfo, #barInfo{display:none;}

JavaScript的:

$('#parentBar').hoverIntent({
    //interval: 500,
    over: function(e) {
        $('#barInfo').show();
    },
    out: function(e) {
        $('#barInfo').hide();
    }
});

$('#childMenu').hoverIntent({
    //interval: 250,
    over: function(e) {
        $('#menuInfo').show();
    },
    out: function(e) {
        $('#menuInfo').hide();
    }
});

$('#childMenu').bind('mouseenter', function(e){
    e.stopPropagation();
});

您可以在jsFiddle:http://jsfiddle.net/hNqQ7/1

上查看

3 个答案:

答案 0 :(得分:2)

var flag = false;
$('#parentBar').hoverIntent({
  interval: 500,
  over: function(e) {
    if(!flag) {
        $('#barInfo').show();
    }
  },
  out: function(e) {
    $('#barInfo').hide();
  }
});

$('#childMenu').hoverIntent({
  interval: 250,
  over: function(e) {
    $('#menuInfo').show();
  },
  out: function(e) {
    $('#menuInfo').hide();
  }
}).mouseenter(function(){
    flag= true;
}).mouseleave(function(){
    flag = false;
});

答案 1 :(得分:1)

在子事件(两个函数)中,调用e.stopPropagation()

编辑: 好的,对不起,我以前没看过这个演示。您可以将子代码更改为以下内容:

$('#childMenu').hoverIntent({
   interval: 250,
   over: function(e) {
        $('#barInfo').hide();
        $('#menuInfo').show();
    },
    out: function(e) {
        $('#barInfo').show();
        $('#menuInfo').hide();
    }
});

答案 2 :(得分:0)

此解决方案修改了核心插件。

使用最新版本的hoverIntent https://github.com/briancherne/jquery-hoverIntent,我对从mouseenter触发的核心功能比较做了一个简单的修改。

查找(〜第65行):

if (Math.sqrt((s.pX - cX) * (s.pX - cX) + (s.pY - cY) * (s.pY - cY)) < cfg.sensitivity) {

并替换为:

if (!$el.hasClass("preventIntent") && Math.sqrt((s.pX - cX) * (s.pX - cX) + (s.pY - cY) * (s.pY - cY)) < cfg.sensitivity) {

这允许您从子/单独交互创建任何逻辑并抑制hoverIntent&#34; over&#34;通过切换类 preventIntent

来起作用

示例:

$(".child-ele").on("mouseenter", function(e) {
    $(this).closest(".parent-ele").addClass("preventIntent");
}).on("mouseleave", function(e) {
    $(this).closest(".parent-ele").removeClass("preventIntent");
});

或者,可以使用&#34; ignoreChild&#34;来改进核心插件。选项选择器,在每个循环上执行.is(&#34;:hover&#34;)的检查。这可以减少额外鼠标事件的需要,但限制它只能显然徘徊。