简体   繁体   中英

jQuery dropdown menu over and out

I have made a small dropdown menu with jQuery and have binded the "show" and "hide" animation on the mouseover/mouseout events. The problem is that when I hover the mouse on the menu list item(s) in my dropdown, the events are trigged and my menu disappears!

I have also tried stopPropagation() which also failed:

$('nav>div.dropTrigger').mouseover(function(e)
{
    console.log("enter");
    $(this).find('div').stop(true,true).animate({ opacity: 'show', height: 'show' },"fast");        
}); 

$('nav>div.dropTrigger').mouseout(function(e)
{   
    console.log("out");
    $(this).find('div').stop(true,true).animate({ opacity: 'hide', height: 'hide' },"fast");        
});

$('.dropdown').mouseover(function(e)
{
    e.stopPropagation();
});

$('.dropdown').mouseout(function(e)
{
    e.stopPropagation();
});

My markup:

<nav>
   <div class="dropTrigger">
      <a href="potatoes">some menu</a>
       <div class="dropdown">
          <ul>[drop menu goes here]
       </div>
 ...

try this:

$('nav>div.dropTrigger').mouseover(function(e)
{
console.log("enter");
$(this).find('div:hidden').stop(true,true).animate({ opacity: 'show', height: 'show'         },"fast");        
}); 

$('nav>div.dropTrigger').mouseout(function(e)
{   
console.log("out");
$(this).find('div:visible').stop(true,true).animate({ opacity: 'hide', height: 'hide'   },"fast");        
});

使用mouseenter / mouseleave代替mouseover / mouseout

$('nav>div.dropTrigger').on({
            mouseenter : function(){ 
                 console.log("enter");
                 $(this).find('div').stop(true,true).animate({ opacity: 'show', height: 'show' },"fast");
            },
            mouseleave : function(){ 
                console.log("out");
                $(this).find('div').stop(true,true).animate({ opacity: 'hide', height: 'hide' },"fast"); 
            }
        });

Bind events to mouseenter and mouseleave instead. They're 'magical' jquery events that attend to the problem your describing. Also - the preferred binding method now is via $.on() (since jq 1.7)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM