带有子元素的JavaScript mouseover / mouseout问题 [英] JavaScript mouseover/mouseout issue with child element

查看:108
本文介绍了带有子元素的JavaScript mouseover / mouseout问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个小问题,我正在请求你的帮助。
我有 div 元素,其中我有 img 元素,就像这样

I have this little problem and I am requesting for your help. I have a div element, inside which I have an img element, like this

<div id="parent" onmouseover="MyFuncHover()" onmouseout="MyFuncOut()">
    <img id="child" src="button.png" style="visibility: hidden" />
</div>

<script type="text/javascript">
    function MyFuncHover() {
        // Here I have some code that makes the "child" visible
    }

    function MyFuncOut() {
        // Here I have some code that makes the "child" invisible again
    }
</script>

正如您所见,图片是 div 的子图片。我希望只有当我离开 div 时,孩子才会消失。然而,看起来当我将鼠标移到图像上时,会调用 MyFuncOut()函数(因为,我想,我通过悬停图像离开div)。我不希望这种情况发生。我希望只有在离开 div 区域时才能调用 MyFuncOut()函数。

As you, see, the image is a child of the div. I want that only when I leave the div, the child to disappear. Yet, it looks like when I move the mouse over the image, the MyFuncOut() function is called (because, I suppose, I leave the div by hovering the image). I don't want that to happen. I want the MyFuncOut() function to be called only when I leave the div area.

我不知道当你将鼠标移到子控件上时,它的父母会调用mouseout事件(即使我超过了孩子,我仍然在父母也是)。我被困在这里,我需要你的一些好建议。谢谢!

I didn't know that when you move your mouse over a child control, it's parent calls the mouseout event (even if I am over the child, I am still over the parent, too). I am trapped into this and I need a little of your good advice. Thanks!

更改

O.K。当我抓出孩子时,事件冒泡不会向父母发送mouseout事件。当我鼠标悬停孩子时,它也不会向父母发送鼠标悬停事件。那不是我需要的。当我鼠标悬停孩子时,我需要父母的mouseout事件不被发送。得到它?当我不希望将子项上的单击事件传播到父项时,事件冒泡很有用,但这不是我的情况。奇怪的是,当我鼠标悬停它们时,我在同一个父级中有其他元素不会触发父级的mouseout事件。

O.K. Event bubbling will not send the "mouseout" event to the parent when I "mouseout" the child. It also won't send the "mouseover" event to the parent when I "mouseover" the child. That's not what I need. I need the "mouseout" event of the parent to not be sent when I "mouseover" the child. Get it? Event bubbling is useful when I don't want, for example, a click event on the child to be propagated to the parent, but this is not my case. What is weird is that I have other elements inside the same parent that don't fire the "mouseout" event of the parent when I "mouseover" them.

推荐答案

你可以在jquery中使用mouseenter和mouseleave事件,这里是下面的代码,

you can use "mouseenter" and "mouseleave" events available in jquery, here is the below code,

$(document).ready(function () {
        $("#parent").mouseenter(function () {
            $("#child").show();
        });
        $("#parent").mouseleave(function () {
            $("#child").hide();
        });
    });

以上是附加活动,

<div id="parent">
    <img id="child" src="button.png" style="display:none;" />
</div>

这篇关于带有子元素的JavaScript mouseover / mouseout问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆