jQuery $.hover used for submenus causing “bouncing

2019-08-27 17:31发布

问题:

I'm having some trouble with the jQuery hover method.

Here's the relevant JavaScript code:

$("#navigation > li > ul").hide();
$("#navigation > li").hover(
    function() {
        $(this).children("ul").slideDown(125);
    },
    function() {
        $(this).children("ul").slideUp(125);
    }
);

Here's the corresponding HTML:

<ul id="navigation">
    <li><a href="#">Top Level Item #1</a></li>
    <li>
        <a href="#">Top Level Item #2</a>
        <ul>
            <li><a href="#">Sub-Menu Item #2-1</a></li>
            <li><a href="#">Sub-Menu Item #2-2</a></li>
            <li><a href="#">Sub-Menu Item #2-3</a></li>
        </ul>
    </li>
</ul>

Whenever you mouseover a top-level item, the submenu in it (if any) will drop down with a nice, quick slide effect. The problem is when you mouseover "into" the menu quickly and keep your mouse where the menu would be but hasn't reached yet: the menu will then hit the "end" of the mouseover animation and bounce back up to the hidden state, and repeat until you remove the mouse from where the dropdown menu would be.

回答1:

Maybe adding a check in the mouseout function could help:

if( !$(this).children("ul").is(":animated") ){
  $(this).children("ul").slideUp(125);
}


回答2:

You could try using hoventIntent, a jQuery plugin that helps with detecting the intent of a user hovering over elements.

http://cherne.net/brian/resources/jquery.hoverIntent.html

I modified your example with it and it seems to behave much nicer. I added:

<script type="text/javascript" language="JavaScript" src="jquery.hoverIntent.minified.js"></script>

and modified the single line with hover() to:

$("#navigation > li").hoverIntent(

I couldn't get it to bounce, and it felt more like a popout menu with the hoverIntent behavior applied.

Lastly, you could try using one of the pre-built jQuery menu plugins as they did all this hard work for you already :)