Javascript MouseOver / MouseOut 子事件

发布于 2024-08-20 13:52:00 字数 126 浏览 10 评论 0原文

我有一个带有一些子元素的元素。当鼠标离开父元素时,我想隐藏父元素及其子元素。我遇到的问题是,当我将鼠标悬停在任何子项上时,将触发 mouseout 事件。防止这种情况的最佳方法是什么?我真的只希望当鼠标不在父级或其任何子级内时触发该事件。

I have an element with some child elements. When the mouse leaves the parent element I want to hide the parent and it's children. Problem I'm having is that when I hover over any of the children, the mouseout event is being fired. What's the best way to prevent this? I really only want the event to fire when the mouse is not within the parent or any of it's children.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

手长情犹 2024-08-27 13:52:00

事件从子级冒泡到父级(在父级中捕获该事件)。

您应该通过添加侦听器并让传播在那里停止来捕获子级上的事件。

此代码将阻止事件冒泡到父级处理程序

function onMouseLeave(e)
{
    if (!e) var e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
}

问题:鼠标关闭事件由父级触发,而本不该触发。将鼠标悬停在子级上不应触发鼠标从父级上移开。我们怎样才能阻止这种情况呢?

The event is bubbling up from the child to the parent (where it is being caught)

You should catch the event on the children by adding a listener and making the propagation stop there.

This code will stop the event from bubbling up to the parents handler

function onMouseLeave(e)
{
    if (!e) var e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
}

question: The mouse off event is fired by the parent, when it should not. Mouseing over the child should not trigger a mouse off from the parent. How can we stop this?

半衾梦 2024-08-27 13:52:00

您只需要一个附加到父元素的 mouseout 处理程序。但是...

您需要检查父级实际上是 mouseout 事件的目标,而不是从子级之一冒泡的事件。检查 event.target (W3C) 和 event.srcElement (IE)。

您还需要检查鼠标将进入的元素是否不是父元素的后代。检查 event.latedTarget (W3C) 和 event.toElement (IE)。

You only need a mouseout handler attached to the parent element. But...

You need to check that the parent is actually the target of the mouseout event, as opposed to the event bubbling up from one of the children. Check event.target (W3C) and event.srcElement (IE).

You also need to check that the element that the mouse will be entering is not a descendant of the parent. Check event.relatedTarget (W3C) and event.toElement (IE).

微暖i 2024-08-27 13:52:00

来自 http://api.jquery.com/mouseover/

mouseover 在指针移入子元素时触发,而 mouseenter 仅在指针移入绑定元素时触发。

mouseoutmouseleave 也是如此

From http://api.jquery.com/mouseover/:

mouseover fires when the pointer moves into the child element as well, while mouseenter fires only when the pointer moves into the bound element.

and the same goes for mouseout vs mouseleave

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文