How do I ignore mouse events on child elements in jQuery?

前端 未结 5 1171
独厮守ぢ
独厮守ぢ 2020-12-08 10:38

I have an unordered list with mouseover and mouseout events attached to the li elements. Each contains a link and there is a bit of padding in the li. When I mouseover the l

相关标签:
5条回答
  • 2020-12-08 11:09

    I was looking for the equivelant behavior in JS where in AS3 you can put:

    object.mouseenabled = false;
    

    The way I found that works pretty well is to use CSS and put:

    .element { pointer-events: none; }
    

    (but I guess that only works if you don't need the element for anything at all. I use it for tooltips that pop up on hover, but don't want it to act weird when you move your mouse away).

    0 讨论(0)
  • 2020-12-08 11:13

    Use "event.stopPropagation()" to stop the events from bubbling upwards:

      jQuery('#menu li a').mouseover( function(evt) {
           evt.stopPropagation();
           return false;
      });
      jQuery('#menu li a').mouseout( function(evt) {
           evt.stopPropagation();
           return false;
      });
    

    Alternatively use the mouseenter and mouseleave events instead of mouseover/out. jQuery normalizes their behaviour across browsers and these events have the benefit of not bubbling...

    0 讨论(0)
  • 2020-12-08 11:22

    You can try this

    $('#menu li').live('mouseenter mouseleave', function (e) {
        if (e.type == 'mouseenter') {
            //Show ul
        } else {
            //Hide ul
        }
    });
    

    The advantage is a usage of event delegation. Good luck!

    0 讨论(0)
  • 2020-12-08 11:22

    Use css classes to distinguish the different menu levels. You can then easily search for one class or the other in your jQuery selectors.

    0 讨论(0)
  • 2020-12-08 11:30

    It seems I've found the answer to my own question. For anyone who might have the same problem; try this code instead. It seems hover doesn't bubble into child elements like the other mouse events do.

    jQuery('#menu li').hover(
        function() {
            jQuery(this).children('ul').show('fast');
            return false;
        },
        function() {
            jQuery(this).children('ul').hide('fast');
            return false;
        }
    );
    
    0 讨论(0)
提交回复
热议问题