MouseOut事件触发不充分

时间:2013-05-25 16:16:07

标签: jquery mouseevent mouseout

我的页面上有这样的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中,为什么事件会被触发?

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

1 个答案:

答案 0 :(得分:1)

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

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

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

另请参阅此 SHORT DEMO

问题的(可能的)原因
关于.mouseover()引用 jQuery's docs “此事件类型可能会因事件冒泡而导致许多令人头疼的问题。例如,当鼠标指针在此示例中移动到Inner元素上时,鼠标悬停事件将被发送到该元素,然后涓流到外部。这可以触发我们绑定的鼠标悬停处理程序在不合时宜的时间。

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