che*_*711 5 html javascript jquery
有许多 jQuery 插件可以让您调整文本大小以适合容器。但是如何动态更改 div 容器的宽度/高度以适应其中的文本呢?
下面举个例子。如您所见,文本当前正在溢出 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>
Run Code Online (Sandbox Code Playgroud)
它应该用 css 完成,但这是在 JS/jQuery 中完成的方法
$('#container').each(function(){
var inner = $(this).find('p');
$(this).height(inner.outerHeight(true));
$(this).width(inner.outerWidth(true));
});
Run Code Online (Sandbox Code Playgroud)
替代解决方案是使用 css 方法设置宽度高度和显示属性
$('#container').css({'width':'auto','height':'auto','display':'table'})
Run Code Online (Sandbox Code Playgroud)