5

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 upon moving the mouse on the child element.

4

3 に答える 3

5

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.

于 2012-06-26T07:46:21.667 に答える
4

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

于 2012-06-26T08:58:30.900 に答える
0

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.

于 2012-06-26T07:46:09.527 に答える