javascript 动态调整容器大小以适应文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22571563/
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
Dynamically resize container to fit text
提问by checkmate711
There are many jQuery plugins that let you resize a text to fit a container. But how can you dynamically change the width/height of a div container to fit the text inside of it?
有许多 jQuery 插件可以让您调整文本大小以适合容器。但是如何动态更改 div 容器的宽度/高度以适应其中的文本?
Below an example. As you can see the text is currently overflowing the div. How can you programatically resize the container div to fit the text independent of the font size and content?
下面举个例子。如您所见,文本当前正在溢出 div。如何以编程方式调整容器 div 的大小以适应与字体大小和内容无关的文本?
<!DOCTYPE html>
<html>
<body>
<div id="container" style="width:100px; height:100px;border:1px solid red; overflow: hidden;">
<p style="font-size:40px;">This is the text</p>
</div>
</body>
</html>
采纳答案by phl
It should be done with css but this is how to do it in JS/jQuery
它应该用 css 来完成,但这是在 JS/jQuery 中如何做到的
$('#container').each(function(){
var inner = $(this).find('p');
$(this).height(inner.outerHeight(true));
$(this).width(inner.outerWidth(true));
});
Alternative solution is to set the width height and display property with the css method
另一种解决方案是使用 css 方法设置宽度高度和显示属性
$('#container').css({'width':'auto','height':'auto','display':'table'})
回答by enapupe
Remove width
and height
, add display:table;
删除width
和height
添加display:table;
回答by Gautam Bhutani
You could decide how do you want the box to fit the text - in width or in height.
您可以决定框如何适应文本 - 宽度或高度。
If you want width, change
如果你想要宽度,改变
width: auto
If you want height, change
如果你想要高度,改变
height: auto
JSFiddle: http://jsfiddle.net/39e7z/
JSFiddle:http: //jsfiddle.net/39e7z/