【问题标题】:MouseOut event triggered inadequatelyMouseOut 事件触发不充分
【发布时间】:2013-05-21 00:42:46
【问题描述】:

我的页面上有这样的 HTML 代码:

<li><img width="100" alt="3Caballeros.png" onmouseover="show_buttons();"</img></li>

当用户悬停图像时,基本上应该会显示几个按钮。 *show_buttons()* 方法应该设置它。这里是:

function show_buttons(item){
var parent =$('img[alt="'+item.alt+'"]').parent();
alert(parent.prop('tagName'));    //says LI
parent.find('img').fadeIn();      //shows the other images in the LI (they are added by JavaScript)
item.onmouseover =function () {};   //removes the event listener to the image
parent.mouseout( parent, function(){
    parent.find('img[alt!="'+item.alt+'"]').fadeOut();
});
parent.mouseover( parent, function(){
    parent.find('img[alt!="'+item.alt+'"]').fadeIn();
});

}

使用 prepend() 方法添加图像,结果类似于:

 <li><img class="first_button" src="images/first.png" style="display: none;">
 <img class="second_button" src="images/second.png" style="display: none;">
 <img width="100" alt="3Caballeros.png" onmouseover="show_buttons();"</img></li>

所以代码几乎没问题:图像在光标进入 LI 时显示,离开时消失。问题是,当光标悬停在 LI 中动态添加的图像之一时,会触发 mouseover 事件,因此图像会消失。这些图像在 LI 中,为什么会触发事件?

我该如何解决这个问题? 谢谢

【问题讨论】:

  • 你能再显示一些代码吗?例如。这些图像究竟是如何动态添加的...
  • 我刚刚编辑了帖子。
  • 当我将fadeIn() 和fadeOut() 替换为show() 和hide() 时,它可以工作......但我仍然希望我的问题得到解答。
  • 嗯...我刚看到这个评论。就像我在回答中所说的那样,除非我对设置(元素布局、CSS 属性等)有更多了解,否则我会在黑暗中拍摄 :)

标签: jquery mouseevent mouseout


【解决方案1】:

我不知道您的确切设置(没有 CSS 等),但以下更改应该可以解决问题:

// Replace 'parent.mouseout(...' with:
parent.mouseleave(...

// Replace 'parent.mouseover(...' with:
parent.mouseenter(...

另请参阅此SHORT DEMO

问题的(可能)原因
引用 jQuery's docs 关于.mouseover():
“由于事件冒泡,这种事件类型会引起很多麻烦。例如,当鼠标指针移动时在这个例子中的 Inner 元素上,一个 mouseover 事件将被发送到该元素,然后滴流到 Outer。这可能会在不合适的时间触发我们绑定的 mouseover 处理程序。

在您的情况下,当从一个图像移动到下一个图像时,会在图像上生成一个 mouseout 事件,然后冒泡到包含 li,从而导致这种意外行为。使用 .mouseenter().mouseleave() 似乎是更好的选择!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-30
    • 2014-06-10
    • 1970-01-01
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    相关资源
    最近更新 更多