How to fire mouse event once for moving over child elements in Javascript?

随声附和 提交于 2019-12-10 15:01:37

问题


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.

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).

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.


回答1:


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);

Fiddle Demo

Reference: Mouse Events




回答2:


What you really need is the mouseenter event, which does not bubble (unlike mouseover). From MDN:

The synchronous mouseenter DOM event is dispatched when a mouse or another pointing device enters the physical space given to the element or one of its descendants.

Similar to mouseover , it differs in that it doesn't bubble and that it isn't sent when the pointer is moved from one of its descendants' physical space to its own physical space.

Unfortunately, it's not widely supported. One solution is to use jQuery (see .mouseenter()), which polyfills that event in all the browsers it supports. Another option is to check the element that triggered the event:

document.getElementById("parent").addEventListener('mouseover', function(e) {
    if (e.target.id === "parent") { //Only execute following on parent mouseover
        document.getElementById("time").innerHTML = new Date;
        this.childNodes[1].style.display="block";
    }
}, false);

Or see here for what looks at first glance to be a pretty good shim.




回答3:


in your example child element is not firing any event it is your parent element on which when you mouseover it runs your script and display result in your "time" div.



来源:https://stackoverflow.com/questions/11202681/how-to-fire-mouse-event-once-for-moving-over-child-elements-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!