本文介绍了如何在Javascript中移动子元素来触发鼠标事件一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输入DOM元素时,将发生 mouseover 事件。在当前元素周围移动鼠标时,不会发生任何事件,因为 mouseover 用于输入。

When entering a DOM element, mouseover event will happen. Upon moving the mouse around the current element, no event happens, as mouseover is for entering.

但是,这子节点不遵守规则。如果将鼠标移到子节点上,则会反复触发鼠标悬停事件,尽管没有新事件,因为我们仍然在原始父节点中。

However, this rule is not obeyed for child nodes. If moving the mouse over child nodes, the mouseover event will be triggered again and again, though no new event, as we are still in the original parent.

请参阅此。如果我们将鼠标移到父项上(实际上是在其textNode上),则不会发生任何新的事情,但如果我们转到子元素(仍然在父元素上),它将触发鼠标悬停事件一次又一次。事实上,每次鼠标进入元素时(即使在原始父元素内),它都会触发鼠标事件。

See this example. If we move the mouse over the parent (actually on its textNode), nothing new happens, but if we go to the child element (still on the parent), it will trigger the mouseover event again and again. In fact it will fire the mouse event every time mouse enters an elements (even inside the original parent element).

我们如何使鼠标悬停只移动一次父级( addEventListener 中的原始元素)?在给定的示例中,我的意思是避免在子元素上移动鼠标时触发事件。

How we can make the mouseover only once for moving all over the parent (the original element in the addEventListener)? In the given example, I mean to avoid firing the event upong moving the mouse on the child element.

推荐答案

这对我有用in chrome和ff

This works for me in chrome and ff

document.getElementById("parent").addEventListener('mouseover', function(event) {
    var e = event.fromElement || event.relatedTarget;
    if (e.parentNode == this || e == this) {
        return;
    }
    document.getElementById("time").innerHTML = new Date();
}, true);

参考:

这篇关于如何在Javascript中移动子元素来触发鼠标事件一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 01:38