【问题标题】:How to get same effect as jQuery's slideToggle using CSS 3 transitions?如何使用 CSS 3 过渡获得与 jQuery 的 slideToggle 相同的效果?
【发布时间】:2012-01-14 06:35:03
【问题描述】:

我想要 jQuery slideToggle 效果,但想使用 CSS3 过渡来调用 iOS 设备上的 GPU,以便过渡更平滑。

【问题讨论】:

  • 我不做 iOS 开发,所以无法测试,但是 move.js 或 animatable 呢?而不是切换,只需要一个 if/else 声明元素所在的位置。

标签: jquery mobile css


【解决方案1】:

您可以通过转换height、padding 和border-width 来实现这一点。这是一个例子:

$('.run-css').click(function() {
    $('.cont').toggleClass('toggled');
});
.cont {
    width: 100px;
    height: 100px;
    border: 1px #CCC solid;
    background-color: #EEE;
    padding: 5px;
    -webkit-transition: height .3s linear, padding-top .3s linear, padding-bottom .3s linear, border-top-width .3s linear, border-top-width .3s linear;
    transition: height .3s linear, padding-top .3s linear, padding-bottom .3s linear, border-top-width .3s linear, border-top-width .3s linear;
}
.toggled {
    overflow: hidden;
    padding-top: 0;
    padding-bottom: 0;
    height: 0;
    border-width: 0 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<button class="run-css">CSS slideToggle</button>

<div class="cont">Toggle this div</div>

【讨论】:

  • 是的。纯 CSS 意味着效果本身不需要 JavaScript。我出于演示目的使用 JS 来切换触发效果的类。
【解决方案2】:

抱歉,除非您知道确切的高度,否则 CSS3 不支持此功能。没有办法在 0 和 auto 之间设置动画。如果你知道确切的高度,你可以在这里生成一些过渡代码:http://css3generator.com/

【讨论】:

  • 这就是我一直在寻找解决方案而没有提及height
【解决方案3】:

没错,您不能在 0 和自动高度之间设置动画,但实际上您可以切换最大高度。

在max-height:0 和max-height:1000px 之间切换(通过JS),你会得到实现的结果,虽然它不会像jQuery 的slideToggle 函数那样流畅。

加上不透明渐变,它看起来很不错。我强烈建议只在相对较短的容器上使用这种技术,因为较大的容器会产生生涩的动画。

【讨论】:

  • 有趣。我玩过这个,并不是容器的大小使它变得生涩......这是max-height和实际内容高度之间的差异。因此,如果您想防止生涩的体验,您可能还需要知道内容高度(如果您知道内容高度,则可以直接过渡到height)。
【解决方案4】:
.container {
    overflow-y: hidden;
    max-height: 0;

    transition: max-height 0.5s ease;
}
.container.open {
    max-height: 1000px; /* approx */
}

【讨论】:

    【解决方案5】:

    我相信Animatable 应该可以解决问题。这是一个 CSS 过渡框架,虽然我不做 iOS 开发,但 Lea Verou 提到她在 FF 和 Chrome for iOS 上测试过它。

    还有其他 CSS 动画库,例如 move.js,它们使用 CSS 过渡和 javascript。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-17
      • 2019-04-10
      • 2014-09-19
      • 2017-04-27
      相关资源
      最近更新 更多