CSS3 equivalent to jQuery slideUp and slideDown?

前端 未结 10 1107
没有蜡笔的小新
没有蜡笔的小新 2020-12-04 08:12

My application is performing poorly with jQuery\'s slideDown and slideUp. I\'m looking to use a CSS3 equivalent in browsers which support it.

Is it possible, using C

10条回答
  •  一生所求
    2020-12-04 08:46

    Aight fam, after some research and experimenting, I think the best approach is to have the thing's height at 0px, and let it transition to an exact height. You get the exact height with JavaScript. The JavaScript isn't doing the animating, it's just changing the height value. Check it:

    function setInfoHeight() {
      $(window).on('load resize', function() {
        $('.info').each(function () {
          var current = $(this);
          var closed = $(this).height() == 0;
          current.show().height('auto').attr('h', current.height() );
          current.height(closed ? '0' : current.height());
        });
      });
    

    Whenever the page loads or is resized, the element with class info will get its h attribute updated. Then you could have a button trigger the style="height: __" to set it to that previously set h value.

    function moreInformation() {
      $('.icon-container').click(function() {
        var info = $(this).closest('.dish-header').next('.info'); // Just the one info
        var icon = $(this).children('.info-btn'); // Select the logo
    
        // Stop any ongoing animation loops. Without this, you could click button 10
        // times real fast, and watch an animation of the info showing and closing
        // for a few seconds after
        icon.stop();
        info.stop();
    
        // Flip icon and hide/show info
        icon.toggleClass('flip');
    
        // Metnod 1, animation handled by JS
        // info.slideToggle('slow');
    
        // Method 2, animation handled by CSS, use with setInfoheight function
        info.toggleClass('active').height(icon.is('.flip') ? info.attr('h') : '0');
    
      });
    };
    

    Here's the styling for the info class.

    .info {
      display: inline-block;
      height: 0px;
      line-height: 1.5em;
      overflow: hidden;
      padding: 0 1em;
      transition: height 0.6s, padding 0.6s;
      &.active {
        border-bottom: $thin-line;
        padding: 1em;
      }
    }
    

    I used this on one of my projects so class names are specific. You can change them up however you like.

    The styling might not be supported cross-browser. Works fine in chrome.

    Below is the live example for this code. Just click on the ? icon to start the animation

    CodePen

提交回复
热议问题