javascript 根据预设“宽度”和“高度”的内容动态改变“div”的高度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25934581/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:15:10  来源:igfitidea点击:

Dynamically change height of "div", based on content with preset "width" and "height"

javascriptjqueryhtmlcssajax

提问by Mia

I have a "div" with preset "width" and "height". I need to change the height of that "div" based on content. I was looking for some JavaScript but couldn't find appropriate for me.

我有一个带有预设“宽度”和“高度”的“div”。我需要根据内容更改“div”的高度。我正在寻找一些 JavaScript,但找不到适合我的。

Here is my simple example, which needs an improvement http://jsfiddle.net/dmitry313/1zr6Lhwa/

这是我的简单示例,需要改进http://jsfiddle.net/dmitry313/1zr6Lhwa/

HTML

HTML

<div id="content">
<h2>Text</h2>
<p>Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example </p> 
</div> 

CSS

CSS

    h2 {
font:18px/30px Arial;
}   
#content {
width:200px;
height:100px;
border:1px solid #000;
background: yellow;
}

EDIT:Initially preset "width" and "height" are important and can't be changed

编辑:最初预设的“宽度”和“高度”很重要,不能改变

回答by ibrahimyilmaz

Just remove heightfrom css. What about that one:

只需height从 css 中删除。那一个呢:

JSFiddle

JSFiddle

Edit: if it can't be changed add overflow: auto;

编辑:如果不能更改添加 overflow: auto;

JSFiddle

JSFiddle

回答by T J

Use min-heightinstead of heightso that the <div>expands accordingly.

使用 min-height代替,height以便相应地<div>扩展。

h2 {
    font:18px/30px Arial;
}
#content {
    width:200px;
    min-height:100px;
    border:1px solid #000;
    background: yellow;
}
<div id="content">
    
<h2>Text</h2>

    <p>Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example Example</p>
</div>

回答by rbrundritt

Try this:

试试这个:

$('#content').height($('#content')[0].scrollHeight)

回答by Florin Pop

I would use height:autolike this;

我会这样使用height:auto

#content {
    height : auto;
}