How to disable mouseout events triggered by child elements?

后端 未结 9 1181
野的像风
野的像风 2020-11-30 21:09

Let me describe the problem in details:

I want to show an absolute positioned div when hovering over an element. That\'s really simple with jQuery and works just fin

相关标签:
9条回答
  • 2020-11-30 21:43

    I'm simply checking if the mouse-coordinates is outside the element in the mouseout-event.

    It works but it's alot of code for such a simple thing :(

    function mouseOut(e)
    {
        var pos = GetMousePositionInElement(e, element);
        if (pos.x < 0 || pos.x >= element.size.X || pos.y < 0 || pos.y >= element.size.Y)
        {
            RealMouseOut();
        }
        else
        {
             //Hit a child-element
        }
    }
    

    Code cut down for readability, won't work out of the box.

    0 讨论(0)
  • 2020-11-30 21:46

    For simplicity sake, I would just reorganize the html a bit to put the newly displayed content inside the element that the mouseover event is bound to:

    <div id="hoverable">
      <a>Hover Me</a>
      <div style="display:none;">
        <input>Test</input>
        <select>
          <option>Option 1</option>
          <option>Option 2</option>
        </select>
      </div>
    </div>
    

    Then, you could do something like this:

    $('#hoverable').hover( function() { $(this).find("div").show(); },
                           function() { $(this).find("div").hide(); } );
    

    Note: I don't recommend inline css, but it was done to make the example easier to digest.

    0 讨论(0)
  • 2020-11-30 21:50

    It's an old question, but it never gets obsolete. The correct answer should be the one given by bytebrite.

    I would only like to point out the difference between mouseover/mouseout and mouseenter/mouseleave. You can read a great and helpful explanation here (go to the very bottom of the page for a working demo). When you use mouseout, the event stops when the mouse enters another element, even if it's a child element. On the other side, when you use mouseleave, the event is not triggered when the mouse overs a child element, and this is the behaviour the OP would like to achieve.

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