gpt4 book ai didi

javascript - 动态调整容器大小以适合文本

转载 作者:搜寻专家 更新时间:2023-10-31 08:31:52 24 4
gpt4 key购买 nike

有许多 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>

最佳答案

它应该用 css 完成,但这是在 JS/jQuery 中的做法

$('#container').each(function(){
var inner = $(this).find('p');
$(this).height(inner.outerHeight(true));
$(this).width(inner.outerWidth(true));
});

http://jsfiddle.net/2CDt5/2/

另一种解决方案是使用 css 方法设置 width height 和 display 属性

$('#container').css({'width':'auto','height':'auto','display':'table'})

http://jsfiddle.net/7yH2t/

关于javascript - 动态调整容器大小以适合文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22571563/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com