如何使用CSS3过渡效果实现与jQuery的slideToggle相同的效果?

22

我希望使用CSS3过渡效果来调用iOS设备上的GPU,以使转换更加流畅,但想要实现jQuery slideToggle效果。


我不从事iOS开发,所以无法测试,但是move.js或animatable怎么样?与其切换,不如使用if/else语句来确定元素的位置。 - David Hobs
6个回答

23

你可以通过对 heightpaddingborder-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>


11
是的,纯CSS意味着效果本身不需要JavaScript。 我在演示中使用了JS来切换触发效果的类。 - dfsq

16

抱歉,除非你知道确切的高度,否则CSS3不支持此操作。无法在0和auto之间进行动画处理。如果您确切地知道高度,可以在此处生成一些过渡代码:http://css3generator.com/


这就是我一直在寻找解决方案而不提及“height”的东西。 - Mo.

6

确实,你不能在0和自动高度之间进行动画,但是你可以切换最大高度。

通过JS在max-height:0max-height:1000px之间切换,你将获得所需的结果,尽管它不会像jQuery的slideToggle函数那样平滑。

结合透明度淡入淡出效果,看起来非常不错。我强烈建议只在相对较短的容器上使用这种技术,因为大容器可能会产生不连贯的动画效果。


1
有趣。我试着玩了一下,发现使它变得卡顿的不是容器的大小,而是max-height和实际内容高度之间的差异。因此,如果你想要避免卡顿的体验(并且如果你知道内容高度,你可以直接过渡到height),你可能也需要知道内容高度。 - bryanbraun

5
.container {
    overflow-y: hidden;
    max-height: 0;

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

0

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

还有其他的CSS动画库,比如move.js,它使用CSS过渡和JavaScript。


0

另一个解决方法是使用 transform: scale3D 和 transform-origin。虽然不完美,但总比没有好。它必须与 show/hide 结合使用。

.slideIn {
  animation-name: slideIn;
  animation-duration: 200ms;
  transform-origin: top;
  animation-timing-function: ease-in;
}

.slideOut {
  animation-name: slideIn;
  animation-duration: 200ms;
  animation-direction: reverse;
  transform-origin: top;
  animation-timing-function: ease-out;
}


@keyframes slideIn {
  from {
    opacity: 0;
    transform: scale3d(1, 0, 0);
  }

  to {
    opacity: 1;
    transform: scale3d(1, 1, 1);
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接