尝试使用 .animate() 而不是 .css()。
$('#foo').animate({'height': '100%'}, 500);
如果你想包含一些easing 效果,你还需要包含jQueryUI 效果,然后代码是:
$('#foo').animate({'height': '100%'}, {easing: 'easeInOutCirc', duration: 500});
编辑:好的,然后为元素创建一个类,例如 .in-transition,它是:
.in-transition{
-webkit-animation: animateHeight 0.5s linear forwards;
-moz-animation: animateHeight 0.5s linear forwards;
-ms-animation: animateHeight 0.5s linear forwards;
-o-animation: animateHeight 0.5s linear forwards;
animation: animateHeight 0.5s linear forwards;
}
@keyframes animateHeight {
0% {
height: (enterCurrentHeight || set it to 0 beforehand);
}
100% {
height: 100%;
}
}
@-webkit-keyframes animateHeight {
0% {
height: (enterCurrentHeight || set it to 0 beforehand);
}
100% {
height: 100%;
}
}
然后您只需添加/删除该类:
$('#foo').on('click', function(){
var this = $(this);
this.addClass('in-transition'); //or use toggleClass
});
解释为(enterCurrentHeight || set it to 0 beforehand):
如果您的#foo 元素在您想要开始动画时已经有一定高度,您需要将动画的height 值设置为该高度作为起点。
例如#foo{height: 60px;} 动画开始前。
在这种情况下,动画的关键帧将如下所示:
@keyframes animateHeight {
0% {
height: 60px;
}
100% {
height: 100%;
}
}
否则,您将获得jump 效果,其中元素的高度将从60px 变为0 (animation start point),然后变为100%。
但是,如果元素的高度事先是0
例如#foo{height: 0;},
您可以将0 设置为动画的起点。
@keyframes animateHeight {
0% {
height: 0;
}
100% {
height: 100%;
}
}
最后的解决方案:好的,现在我明白了您的问题,但您无法使用 .css() 解决它。我的建议是,不要在load 上创建和附加#foo 元素,而是直接在您的HTML 中创建它。因为它的初始height 被CSS 定义为0,所以它不会被看到。然后你只需要在load 上添加.in-transition 类。
Notice: #(id) 选择器优于.(class) 选择器,因此您需要将.in-transition 附加到#foo,例如#foo.in-transition,非常重要
HTML:
<div id="foo"></div>
CSS:
#foo{
height: 0;
width: 100px;
background: red;
transition: all 0.5s ease;
-webkit-transition: all 0.5s ease;
}
#foo.in-transition{
height: 100px;
}
JS:
(function(){
var $foo = $('#foo');
$foo.addClass('in-transition');
}
工作示例:http://jsfiddle.net/31d57n55/5/
伙计,说一个长答案。