动态调整容器大小以适合文本 [英] Dynamically resize container to fit text

查看:112
本文介绍了动态调整容器大小以适合文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有许多jQuery插件可让您调整文本大小以适应容器。但是,如何动态更改div容器的宽度/高度以适合其中的文本?

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?

下面的示例。正如您所看到的,文本当前正在溢出div。如何编程调整容器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?

   <!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中执行

It should be done with css but this is how to do it in 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方法设置宽度高度和显示属性

Alternative solution is to set the width height and display property with the css method

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

http://jsfiddle.net/7yH2t/

这篇关于动态调整容器大小以适合文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆