如何使用CSS 3过渡获得与jQuery的slideToggle相同的效果?

sev*_*ens 20 css mobile jquery css3

我想要jQuery slideToggle效果,但想要使用CSS3过渡以便在iOS设备上调用GPU,以便过渡更顺畅.

dfs*_*fsq 21

您可以通过转换实现这一点height,padding的和border-width.这是一个例子:

$('.run-css').click(function() {
    $('.cont').toggleClass('toggled');
});
Run Code Online (Sandbox Code Playgroud)
.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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

  • 是的.纯CSS意味着效果本身不需要JavaScript.我使用JS进行演示,以切换触发效果的类. (11认同)

Tel*_*iRE 15

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


Car*_*son 6

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

max-height:0和之间(通过JS)进行切换max-height:1000px,您将获得所获得的结果,尽管它不如jQuery的slideToggle函数那么平滑。

加上不透明的褪色效果,看起来还不错。但我强烈建议您仅在相对较短的容器上使用此技术,因为较大的容器可以创建生涩的动画。


Joh*_*n F 5

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

    transition: max-height 0.5s ease;
}
.container.open {
    max-height: 1000px; /* approx */
}
Run Code Online (Sandbox Code Playgroud)