ToggleClass animate jQuery?

后端 未结 6 2043
生来不讨喜
生来不讨喜 2020-12-01 18:05

I have a section on my website that when a user clicks I would like it to expand, I\'m using the jQuery\'s toggleClass for this...

expandable: f         


        
相关标签:
6条回答
  • 2020-12-01 18:14

    You can simply use CSS transitions, see this fiddle

    .on {
    color:#fff;
    transition:all 1s;
    }
    
    .off{
    color:#000;
    transition:all 1s;
    }
    
    0 讨论(0)
  • 2020-12-01 18:17

    I attempted to use the toggleClass method to hide an item on my site (using visibility:hidden as opposed to display:none) with a slight animation, but for some reason the animation would not work (possibly due to an older version of jQuery UI).

    The class was removed and added correctly, but the duration I added did not seem to make any difference - the item was simply added or removed with no effect.

    So to resolve this I used a second class in my toggle method and applied a CSS transition instead:

    The CSS:

    .hidden{
        visibility:hidden;
        opacity: 0;
        -moz-transition: opacity 1s, visibility 1.3s;
        -webkit-transition: opacity 1s, visibility 1.3s;
        -o-transition: opacity 1s, visibility 1.3s;
        transition: opacity 1s, visibility 1.3s;
    }
    .shown{
        visibility:visible;
        opacity: 1;
        -moz-transition: opacity 1s, visibility 1.3s;
        -webkit-transition: opacity 1s, visibility 1.3s;
        -o-transition: opacity 1s, visibility 1.3s;
        transition: opacity 1s, visibility 1.3s;
    }
    

    The JS:

        function showOrHide() {
            $('#element').toggleClass("hidden shown");
        }
    

    Thanks @tomas.satinsky for the awesome (and super simple) answer on this post.

    0 讨论(0)
  • 2020-12-01 18:17

    You should look at the toggle function found on jQuery. This will allow you to specify an easing method to define how the toggle works.

    slideToggle will only slide up and down, not left/right if that's what you are looking for.

    If you need the class to be toggled as well you can deifine that in the toggle function with a:

    $(this).closest('article').toggle('slow', function() {
        $(this).toggleClass('expanded');
    });
    
    0 讨论(0)
  • 2020-12-01 18:21

    .toggleClass() will not animate, you should go for slideToggle() or .animate() method.

    0 讨论(0)
  • 2020-12-01 18:21

    Should have checked, Once I included the jQuery UI Library it worked fine and was animating...

    0 讨论(0)
  • 2020-12-01 18:31

    jQuery UI extends the jQuery native toggleClass to take a second optional parameter: duration

    toggleClass( class, [duration] )
    

    Docs + DEMO

    0 讨论(0)
提交回复
热议问题