简体   繁体   中英

Smooth toggle in jQuery

I am using some simple jQuery to animate a toggle button. The toggle works, however, no matter how I try changing values, I cannot seem to change the speed or smoothness of the animation.

I have looked at different methods and tried changing the values within the .sliderUp section, it just isn't working for me.

The code I am using is:

$(document).ready(function(){
    $("a.toggle").click(function(){
        if ($("nav ul").hasClass("expanded")) {
            $("nav ul.expanded").removeClass("expanded").slideUp(250);
            $(this).removeClass("open");
        } else {
            $("nav ul").addClass("expanded").slideDown(250);
            $(this).addClass("open");
        }
    });
});

-

<nav>
    <a href="#" class="toggle">Toggle Menu</a>
    <ul>
        <li>Menu Item</li>
        <li>Menu Item</li>
    </ul>
</nav>

-

nav {
    width: 100%;

    ul {
        display: none;
        width: 100%;

        &.expanded {
            display: block;
        }
    }

    .toggle {
        display: block !important;
    }
}

Try to use slideToggle

Syntax

$(selector).slideToggle(speed,callback);

Here the optional speed parameter can take the following values: "slow", "fast", milliseconds .

So i think you need to put more time to get smooth animation.

Jquery

$(document).ready(function(){
  $("a.toggle").click(function(){
    $("nav ul").slideToggle(1500);
    $(this).toggleClass("open");
  });
});

Here is the working jsfiddle: https://jsfiddle.net/88bm4x6z/1/

If any of you still not been able to slide smoothly, just set transition: none; . if you'r using it in your parent item or child, I stuck in it for 3 hours. Then I just set it to none, it worked.

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