简体   繁体   中英

How to improve jQuery drop down menu animation

I have created a simple jQuery drop down menu using the slideUp and slideDown functions. It works if the user would slowly hover over each allowing the previous one to finish but that would never happen in reality.

How would I go about improving the code so it would be a smooth transition for each dropdown?

Here is a working fiddle of my dilema: jsfiddle and here is the code:

HTML

<div id="header">
  <a id="item1" class="item" href="">Item 1</a>
  <a id="item2" class="item"  href="">Item 2</a>
</div>

<div id="box1">box1</div>
<div id="box2">box2</div>

CSS

#header{
    width:100%;
    height:50px;
    background:blue;
    text-align:right;
}

.item{
    color:#fff;
    width:50px;
    height:50px;
    display:inline-block;
    background:gray;
}

#box1{
    width:200px;
    height:100px;
    background:gray;
    display:none;
    float:right;
}

#box2{
    width:200px;
    height:100px;
    background:gray;
    display:none;
    float:right;
}

jQuery

$('#item1').hover(function(){
   $('#box1').stop().slideDown();
}, function(){
   $('#box1').stop().slideUp();
});

$('#item2').hover(function(){
   $('#box2').stop().slideDown();
}, function(){
   $('#box2').stop().slideUp();
});

Specifies the speed of the slide effect.
Possible values:

  1. milliseconds
  2. slow
  3. fast

检查这种很棒的方法,让您仅将鼠标悬停在动画上而不是过滤后,这将解决您的问题。

 $('#box1').filter(':not(:animated)').slideUp();

The key is using promise() to waint until animation is ended.

You can check how its work there: http://jsfiddle.net/mcXBB/4/

I also changed your events to more flexible way which allow you to handle more menu positions in easier way:

<div id="header">
    <a id="item1" class="item" rel="#box1" href="">Item 1</a>
    <a id="item2" class="item" rel="#box2" href="">Item 2</a>
</div>

<div id="box1" class="boxes" >box1</div>
<div id="box2" class="boxes" >box2</div>

$('#header a')
.mouseenter( function() {
    var boxId = $(this).attr('rel');
    $('.boxes').promise().done( function() {
        $(boxId).slideDown();
    });

})
.mouseleave(function() {
    var boxId = $(this).attr('rel');
    $('.boxes').promise().done( function() {
        $(boxId).slideUp();
    });
});

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