CSS 具有基于内容动态变化高度的div的webkit-transition高度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6588510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
webkit-transition height for a div with a dynamic changing height based on content?
提问by TheExit
please see the following jsFiddle
请看下面的jsFiddle
You can click the various buttons which shows different length content which causes the box to grow/shrink.
您可以单击显示不同长度内容的各种按钮,这会导致框增大/缩小。
I want the height change to be animated so it is not so jumpy, I tried this by adding:
我希望高度变化是动画的,所以它不是那么跳跃,我通过添加:
-webkit-transition: all 1s linear;
But that has no effect in this use case. Any ideas in terms of a solution that doesn't require JavaScript?
但这在这个用例中没有影响。关于不需要 JavaScript 的解决方案的任何想法?
Thanks
谢谢
回答by methodofaction
I'm afraid there is no way of animating height with CSS3 transitions without some Javascript assistance, check out:
如果没有一些 Javascript 帮助,恐怕没有办法用 CSS3 过渡动画高度,请查看:
How can I transition height: 0; to height: auto; using CSS?
Can you use CSS3 to transition from height:0 to the variable height of content?
你能用 CSS3 从 height:0 过渡到内容的可变高度吗?
Additionally, your code goes from display: none to display: block, which wouldn't have an effect on height in any case. Instead of display none use height: 0 with overflow: hidden;
此外,您的代码从 display: none 到 display: block,这在任何情况下都不会影响高度。而不是 display none 使用 height: 0 with overflow: hidden;
回答by YArea
It has been 8 years, but for those who look for the solution to this request:
已经 8 年了,但对于那些寻求解决此要求的人来说:
CSS
CSS
#box {
border: 1px solid gray;
background-color: #f3f3f3;
-webkit-transition: all 1s linear;
}
.content {display:none}
.new_content {
transition: 1s;
}
JS
JS
$('.toggler').on('click', function() {
var idname = $(this).attr('name');
var content = $('#' + idname).html();
var content_height = $('#' + idname).height();
$('.new_content').html(content).css("height", content_height);
});
Also, what has been changed:
此外,还有哪些变化:
- You don't use anymore "display: none" and "display: block" as the method you are based on. You prefer to use content replacement of a static shown div
- The content div ('.new_content') doesn't have a height, its optional.
- The JS sets the height based on the hidden div.
- The transition does the job.
- 您不再使用“display:none”和“display:block”作为您所基于的方法。您更喜欢使用静态显示 div 的内容替换
- 内容 div ('.new_content') 没有高度,它是可选的。
- JS 根据隐藏的 div 设置高度。
- 过渡完成了这项工作。
Hope it helps.
希望能帮助到你。