menu mouseenter mouseleave click

2019-02-25 17:55发布

问题:

Anyone can help me? I want a dropdown menu with animation on mouseenter and mouseleave events but when clicked after mouse enter I want the submenu stay visible until new click anywhere in page (in the example is only in the body). After that second click (same animation of mouseleave) I want mouseenter and mouseleave .on again like when we started.

$('#menu > li').on('mouseenter',function(){
    //mouseenter handler
});

$('#menu > li').on('mouseleave',function(){
    //mouseleave handler
});
$('#menu > li').toggle(
  function () {
  $('#menu > li').off('mouseenter mouseleave');
  },
  function () {
  //mouseleave handler
  });
$('body').click(function(){
  //same mouseleave handler
});

I don't know how i can enable mouseenter/mouseleave after second click. Sorry, and thanks.

回答1:

This could be significantly simplified using event delegation:

$('document').on("click",'#menu > li', function() {
    $('#menu > li').off('mouseenter mouseleave');
});

$('document').on("click",':not(#menu > li)', function() {
    $('#menu > li').on('mouseenter', function(){
         //your mouseenter handler goes here
    });
    $('#menu > li').on('mouseleave', function(){
         //your mouseleave handler goes here
    });
});

This is semantically equivalent to:

If a click happens on a menu item, unbind mouse enter/leave events

If a click happens on a non menu item, bind mouse enter/leave events