【问题标题】:CSS3 equivalent to jQuery slideUp and slideDown?CSS3 相当于 jQuery slideUp 和 slideDown?
【发布时间】:2011-07-01 15:31:30
【问题描述】:

我的应用程序在使用 jQuery 的 slideDown 和 slideUp 时表现不佳。我希望在支持它的浏览器中使用等效的 CSS3。

是否可以在向下或向上滑动项目时使用 CSS3 过渡将元素从 display: none; 更改为 display: block;

【问题讨论】:

  • 我认为你会保留显示:块,但只需将宽度从所需数量调整为 0。

标签: jquery css animation


【解决方案1】:

没有 JavaScript 的变体。只有 CSS。

CSS:

.toggle_block {
    border: 1px solid #ccc;
    text-align: left;
    background: #fff;
    overflow: hidden;
}
.toggle_block .toggle_flag {
    display: block;
    width: 1px;
    height: 1px;
    position: absolute;
    z-index: 0;
    left: -1000px;
}
.toggle_block .toggle_key {
    font-size: 16px;
    padding: 10px;
    cursor: pointer;
    -webkit-transition: all 300ms ease;
       -moz-transition: all 300ms ease;
        -ms-transition: all 300ms ease;
         -o-transition: all 300ms ease;
            transition: all 300ms ease;
}
.toggle_block .content {
    padding: 0 10px;
    overflow: hidden;
    max-height: 0;
    -webkit-transition: all 300ms ease;
       -moz-transition: all 300ms ease;
        -ms-transition: all 300ms ease;
         -o-transition: all 300ms ease;
            transition: all 300ms ease;
}
.toggle_block .content .toggle_close {
    cursor: pointer;
    font-size: 12px;
}
.toggle_block .toggle_flag:checked ~ .toggle_key {
    background: #dfd;
}
.toggle_block .toggle_flag:checked ~ .content {
    max-height: 1000px;
    padding: 10px 10px;
}

HTML:

<div class="toggle_block">
    <input type="checkbox" id="toggle_1" class="toggle_flag">
    <label for="toggle_1" class="toggle_key">clicker</label>
    <div class="content">
        Text 1<br>
        Text 2<br>
        <label for="toggle_1" class="toggle_close">close</label>
    </div>
</div>

对于下一个块,仅更改 html 中的 ID 和 FOR 属性。

【讨论】:

    【解决方案2】:
        try this for slide up slide down with animation 
    give your **height
    
            @keyframes slide_up{
                from{
                    min-height: 0;
                    height: 0px;
                    opacity: 0;
                }
                to{
                    height: 560px;
                    opacity: 1;
                }
            }
    
            @keyframes slide_down{
                from{
                    height: 560px;
                    opacity: 1;
                }
                to{
                    min-height: 0;
                    height: 0px;
                    opacity: 0;
                } 
            }
    

    【讨论】:

      【解决方案3】:

      所以我继续回答我自己的问题:)

      @True 的回答是将元素转换为特定高度。问题是我不知道元素的高度(它可能会波动)。

      我找到了其他使用 max-height 作为过渡的解决方案,但这对我来说产生了非常生涩的动画。

      以下我的解决方案仅适用于 WebKit 浏览器。

      虽然不是纯粹的 CSS,但它涉及到过渡高度,这是由一些 JS 决定的。

      $('#click-me').click(function() {
        var height = $("#this").height();
        if (height > 0) {
          $('#this').css('height', '0');
        } else {
          $("#this").css({
            'position': 'absolute',
            'visibility': 'hidden',
            'height': 'auto'
          });
          var newHeight = $("#this").height();
          $("#this").css({
            'position': 'static',
            'visibility': 'visible',
            'height': '0'
          });
          $('#this').css('height', newHeight + 'px');
        }
      });
      #this {
        width: 500px;
        height: 0;
        max-height: 9999px;
        overflow: hidden;
        background: #BBBBBB;
        -webkit-transition: height 1s ease-in-out;
      }
      
      #click-me {
        cursor: pointer;
      }
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
      
      <p id="click-me">click me</p>
      <div id="this">here<br />is<br />a<br />bunch<br />of<br />content<br />sdf</div>
      <div>always shows</div>

      View on JSFiddle

      【讨论】:

      • 是的,我下面的代码不需要高度,因为它使用 y 坐标。但是您没有提到您需要具有高度依赖性的东西:) 您总是可以进行边距转换等。但是看起来您已经找到了您想要的东西,不是吗?
      • @True 你认为你能解释一下边距过渡是什么意思吗?
      • 添加了定位样本,将添加边距
      • 还添加了边距/无 javsacript 示例
      【解决方案4】:

      你可以这样做:

      #youritem .fade.in {
          animation-name: fadeIn;
      }
      
      #youritem .fade.out {
          animation-name: fadeOut;
      }
      
      @keyframes fadeIn {
          0% {
              opacity: 0;
              transform: translateY(startYposition);
          } 
          100% {
              opacity: 1;
              transform: translateY(endYposition);
          }
      }
      
      @keyframes fadeOut {
          0% {
              opacity: 1;
              transform: translateY(startYposition);
          } 
          100% {
              opacity: 0;
              transform: translateY(endYposition);
          }
      }
      

      示例 - 滑动和淡出:

      这会滑动和动画不透明度 - 不是基于容器的高度,而是基于顶部/坐标。 View example

      示例 - 自动高度/无 Javascript: 这是一个实时示例,不需要高度 - 处理自动高度并且没有 javascript。
      View example

      【讨论】:

      • 你能在jsFiddle上做一个demo吗?
      • @Šime 从我第一次看它,我会说只要给你的元素 class="fade" 并在你想要淡入时添加类,当你想要淡入时添加类淡出。
      • @Šime - 我提供了两个示例供您使用
      • 我修改了第二个示例(自动高度/无 JavaScript),因此只有获得效果的准系统样式就位。 jsfiddle.net/OlsonDev/nB5Du/251
      • @Olson.dev 谢谢,好多了。
      【解决方案5】:

      Aight fam,经过一些研究和实验,我认为最好的方法是将物体的高度设置为0px,然后让它过渡到一个精确的高度。您可以使用 JavaScript 获得准确的高度。 JavaScript 不做动画,它只是改变高度值。检查它:

      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());
          });
        });
      

      每当页面加载或调整大小时,类info 的元素将更新其h 属性。然后你可以有一个按钮触发style="height: __" 将其设置为之前设置的h 值。

      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');
      
        });
      };
      

      这是info 类的样式。

      .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;
        }
      }
      

      我在我的一个项目中使用了这个,所以类名是特定的。您可以随意更改它们。

      样式可能不支持跨浏览器。在 chrome 中运行良好。

      以下是此代码的实时示例。只需点击? 图标即可开始动画

      CodePen

      【讨论】:

        【解决方案6】:

        为什么不利用现代浏览器的 css 转换,使用更多的 css 和更少的 jquery 让事情变得更简单和快速

        Here is the code for sliding up and down

        Here is the code for sliding left to right

        同样,我们可以通过适当地改变 transform-origin 和 transform: scaleX(0) 或 transform: scaleY(0) 来改变从上到下或从右到左的滑动。

        【讨论】:

        • 我知道这个答案是在 2014 年发布的,但如果你想将其下方的元素向下或向上推,我不建议使用此答案,因为父容器会占用浏览器中的高度
        • 这可以通过将元素放在绝对位置上来解决 @Ellisan,例如,非常适合菜单的效果
        【解决方案7】:

        让高度过渡起作用可能有点棘手,主要是因为您必须知道要为其设置动画的高度。通过在要设置动画的元素中进行填充,这进一步复杂化了。

        这是我想出的:

        使用这样的样式:

            .slideup, .slidedown {
                max-height: 0;            
                overflow-y: hidden;
                -webkit-transition: max-height 0.8s ease-in-out;
                -moz-transition: max-height 0.8s ease-in-out;
                -o-transition: max-height 0.8s ease-in-out;
                transition: max-height 0.8s ease-in-out;
            }
            .slidedown {            
                max-height: 60px ;  // fixed width                  
            }
        

        将您的内容包装到另一个容器中,以便您滑动的容器没有填充/边距/边框:

          <div id="Slider" class="slideup">
            <!-- content has to be wrapped so that the padding and
                    margins don't effect the transition's height -->
            <div id="Actual">
                    Hello World Text
                </div>
          </div>
        

        然后使用一些脚本(或绑定框架中的声明性标记)来触发 CSS 类。

          $("#Trigger").click(function () {
            $("#Slider").toggleClass("slidedown slideup");
          });
        

        这里的例子: http://plnkr.co/edit/uhChl94nLhrWCYVhRBUF?p=preview

        这适用于固定大小的内容。对于更通用的解决方案,您可以使用代码来计算激活转换时元素的大小。以下是一个 jQuery 插件,可以做到这一点:

        $.fn.slideUpTransition = function() {
            return this.each(function() {
                var $el = $(this);
                $el.css("max-height", "0");
                $el.addClass("height-transition-hidden");
            });
        };
        
        $.fn.slideDownTransition = function() {
            return this.each(function() {
                var $el = $(this);
                $el.removeClass("height-transition-hidden");
        
                // temporarily make visible to get the size
                $el.css("max-height", "none");
                var height = $el.outerHeight();
        
                // reset to 0 then animate with small delay
                $el.css("max-height", "0");
        
                setTimeout(function() {
                    $el.css({
                        "max-height": height
                    });
                }, 1);
            });
        };
        

        可以这样触发:

        $("#Trigger").click(function () {

            if ($("#SlideWrapper").hasClass("height-transition-hidden"))
                $("#SlideWrapper").slideDownTransition();
            else
                $("#SlideWrapper").slideUpTransition();
        });
        

        反对这样的标记:

        <style>
        #Actual {
            background: silver;
            color: White;
            padding: 20px;
        }
        
        .height-transition {
            -webkit-transition: max-height 0.5s ease-in-out;
            -moz-transition: max-height 0.5s ease-in-out;
            -o-transition: max-height 0.5s ease-in-out;
            transition: max-height 0.5s ease-in-out;
            overflow-y: hidden;            
        }
        .height-transition-hidden {            
            max-height: 0;            
        }
        </style>
        <div id="SlideWrapper" class="height-transition height-transition-hidden">
            <!-- content has to be wrapped so that the padding and
                margins don't effect the transition's height -->
            <div id="Actual">
             Your actual content to slide down goes here.
            </div>
        </div>
        

        示例: http://plnkr.co/edit/Wpcgjs3FS4ryrhQUAOcU?p=preview

        如果您有兴趣了解更多细节,我最近在一篇博文中写了这篇文章:

        http://weblog.west-wind.com/posts/2014/Feb/22/Using-CSS-Transitions-to-SlideUp-and-SlideDown

        【讨论】:

        • 这对我来说是最优雅的解决方案。如果需要,可以轻松删除 jQuery。可以将 vanila JS 中的类切换为:document.getElementById("Slider").classList.toggle("slidedown");
        【解决方案8】:

        你不能用 css3 轻松地进行滑动,这就是为什么我将 JensT 脚本变成了一个带有 javascript 回退和回调的插件。

        这样,如果您有一个现代浏览器,您可以使用 css3 csstransition。如果您的浏览器不支持它,请优雅地使用老式的 slideUp slideDown。

         /* css */
        .csstransitions .mosneslide {
          -webkit-transition: height .4s ease-in-out;
          -moz-transition: height .4s ease-in-out;
          -ms-transition: height .4s ease-in-out;
          -o-transition: height .4s ease-in-out;
          transition: height .4s ease-in-out;
          max-height: 9999px;
          overflow: hidden;
          height: 0;
        }
        

        插件

        (function ($) {
        $.fn.mosne_slide = function (
            options) {
            // set default option values
            defaults = {
                delay: 750,
                before: function () {}, // before  callback
                after: function () {} // after callback;
            }
            // Extend default settings
            var settings = $.extend({},
                defaults, options);
            return this.each(function () {
                var $this = $(this);
                //on after
                settings.before.apply(
                    $this);
                var height = $this.height();
                var width = $this.width();
                if (Modernizr.csstransitions) {
                    // modern browsers
                    if (height > 0) {
                        $this.css(
                            'height',
                            '0')
                            .addClass(
                                "mosne_hidden"
                        );
                    } else {
                        var clone =
                            $this.clone()
                            .css({
                                'position': 'absolute',
                                'visibility': 'hidden',
                                'height': 'auto',
                                'width': width
                            })
                            .addClass(
                                'mosne_slideClone'
                        )
                            .appendTo(
                                'body'
                        );
                        var newHeight =
                            $(
                                ".mosne_slideClone"
                        )
                            .height();
                        $(
                            ".mosne_slideClone"
                        )
                            .remove();
                        $this.css(
                            'height',
                            newHeight +
                            'px')
                            .removeClass(
                                "mosne_hidden"
                        );
                    }
                } else {
                    //fallback
                    if ($this.is(
                        ":visible"
                    )) {
                        $this.slideUp()
                            .addClass(
                                "mosne_hidden"
                        );
                    } else {
                        $this.hide()
                            .slideDown()
                            .removeClass(
                                "mosne_hidden"
                        );
                    }
                }
                //on after
                setTimeout(function () {
                    settings.after
                        .apply(
                            $this
                    );
                }, settings.delay);
            });
        }
        })(jQuery);;
        

        如何使用它

        /* jQuery */
        $(".mosneslide").mosne_slide({
            delay:400,
            before:function(){console.log("start");},
            after:function(){console.log("done");}
        });
        

        您可以在此处找到演示页面 http://www.mosne.it/playground/mosne_slide_up_down/

        【讨论】:

        • 这不是答案,答案不仅仅是一个链接。
        • 这没有提供问题的答案。要批评或要求作者澄清,请在他们的帖子下方发表评论 - 您可以随时评论自己的帖子,一旦您有足够的reputation,您就可以comment on any post
        • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接的答案可能会失效。
        【解决方案9】:

        我建议使用jQuery Transit Plugin,它使用 CSS3 转换属性,由于大多数支持硬件加速以提供原生外观和感觉,因此该属性在移动设备上运行良好。

        JS Fiddle Example

        HTML:

        <div class="moveMe">
            <button class="moveUp">Move Me Up</button>
            <button class="moveDown">Move Me Down</button>
            <button class="setUp">Set Me Up</button>
            <button class="setDown">Set Me Down</button>
         </div>
        

        Javascript:

        $(".moveUp").on("click", function() {
            $(".moveMe").transition({ y: '-=5' });
        });
        
        $(".moveDown").on("click", function() {
            $(".moveMe").transition({ y: '+=5' });
        });
        
        $(".setUp").on("click", function() {
            $(".moveMe").transition({ y: '0px' });
        });
        
        $(".setDown").on("click", function() {
            $(".moveMe").transition({ y: '200px' });
        });
        

        【讨论】:

        • 这是否使您能够使用自动转换到元素的自然高度?例如。 $(".moveMe").transition({height: 'auto'})
        • 我希望他们用这个插件覆盖 slideUp()slideDown() 方法。那就太好了
        • 这太棒了顺便说一句。感谢您添加此答案!
        【解决方案10】:

        我更改了您的解决方案,使其适用于所有现代浏览器:

        css sn-p:

        -webkit-transition: height 1s ease-in-out;
        -moz-transition: height 1s ease-in-out;
        -ms-transition: height 1s ease-in-out;
        -o-transition: height 1s ease-in-out;
        transition: height 1s ease-in-out;
        

        js sn-p:

            var clone = $('#this').clone()
                        .css({'position':'absolute','visibility':'hidden','height':'auto'})
                        .addClass('slideClone')
                        .appendTo('body');
        
            var newHeight = $(".slideClone").height();
            $(".slideClone").remove();
            $('#this').css('height',newHeight + 'px');
        

        这是完整的例子http://jsfiddle.net/RHPQd/

        【讨论】:

        • 不确定是谁-2 这个,7 年后,仍然像魅力一样工作。除了我用 Vanilla JS 重新创建它。 +1来自我。
        猜你喜欢
        • 2017-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-11
        • 1970-01-01
        相关资源
        最近更新 更多