[removed] Multiple mouseout events triggered

前端 未结 1 1590
情歌与酒
情歌与酒 2020-12-17 02:50

I\'m aware of the different event models in Javascript (the WC3 model versus the Microsoft model), as well as the difference between bubbling and capturing. However, after

相关标签:
1条回答
  • 2020-12-17 03:47

    The mouseout event on the inner div ‘bubbles’ to the outer div. To detect that this has happened from the outer div, check the target property of the event:

    <div id="outer">
        <div id="inner">x</div>
    </div>
    
    document.getElementById('outer').onmouseout= function(event) {
        // deal with IE nonsense
        if (event===undefined) event= window.event;
        var target= 'target' in event? event.target : event.srcElement;
    
        if (target!==this) return;
        ...
    };
    

    The usual problem with mouseout is you get it when the pointer moves “out” of the parent even if it's only moving “in” to the child. You can detect this case manually by looking up the ancestor list of the element the mouse is moving into:

        var other= 'relatedTarget' in event? event.relatedTarget : event.toElement;
        while ((other= other.parentNode).nodeType===1)
            if (other===this) return;
    

    This is the mousein/mouseout model: it is only interested about which element is the mouse's immediate parent. What you more often want is the mouseenter/mouseleave model, which considers element trees as a whole, so you'd only get mouseleave when the pointer was leaving the element-or-its-descendants and not moving directly into the element-or-its-descendants.

    Unfortunately mouseenter/mouseleave is currently an IE-only event pair. Hopefully other browsers will pick it up as it is expected to be part of DOM Level 3 Events.

    0 讨论(0)
提交回复
热议问题