【问题标题】:Dynamically change height of "div", based on content with preset "width" and "height"根据预设“width”和“height”的内容动态改变“div”的高度
【发布时间】:2014-09-19 21:51:58
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 你为什么不用height: auto;
  • 您设置的最小预期尺寸是多少?还是 div 应该变成 0 高度和宽度?
  • @Alex 最初预设的“宽度”和“高度”很重要,不能更改

标签: javascript jquery html css ajax


【解决方案1】:

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

JSFiddle

编辑:如果无法更改添加overflow: auto;

JSFiddle

【讨论】:

  • 初始预设的“宽度”和“高度”很重要,不能更改
  • 如果你想动态改变它的高度写一些js:"$('#content').css('height','auto');"
  • 不能从预设条件改变,但可以根据内容改变
【解决方案2】:

使用min-height 代替height,以便&lt;div&gt; 相应地扩展。

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>

【讨论】:

  • 假设我有三个像上面一样的 div。假设来自一个 div 的数据随着 div 高度的增加而增加。如果我想根据第一个 div 的高度增加另外 2 个相邻 div 的高度,即使它有更少的单词要换行。我们怎样才能实现这个场景?你能帮帮我吗
  • @PrasannaSasne css-tricks.com/fluid-width-equal-height-columns 看看这个博客中的弹性盒子方法。如果这是关于页面的核心布局而不仅仅是一些小元素,CSS 网格也可以实现这一点
  • 感谢您的帮助:)
【解决方案3】:

试试这个:

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

【讨论】:

  • 太棒了!!谢谢
【解决方案4】:

我会像这样使用height:auto

#content {
    height : auto;
}

【讨论】:

  • 初始预设的“宽度”和“高度”很重要,不能更改
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-16
  • 2016-09-27
  • 1970-01-01
相关资源
最近更新 更多