简体   繁体   English

根据动态内容动态调整div的大小?

[英]Dynamically resize div according to dynamic content?

I have a div called container which contains dynamically created content(paragraphs) through javascript. 我有一个称为容器的div,其中包含通过javascript动态创建的内容(段落)。 The problem is that the paragphs aren't shown on the div once they reach beyond the boundaries of the container. 问题在于,一旦它们超出了容器的边界,就不会在div上显示它们。 To solve this issue, I tried overflow but that just added x,y scrollbars. 为了解决这个问题,我尝试了溢出,但是只添加了x,y滚动条。

What I'm trying to do is increase the height of the container after every parapgraph added ie when paragraph is added to container of height 20px, the container increases height to a further 40 px for next paragraph. 我想做的是在添加每个段落后增加容器的高度,即当将段落添加到高度为20px的容器时,容器将高度增加到下一个段落的40 px。

HTML 的HTML

<div class="container"></div>

<a href="#" id="add">Add content</a>

CSS 的CSS

.container {
width: 120px;
height: 20px;
display: inline-block;
margin-left: auto;
margin-right: auto;
/* overflow: auto; */  //As aforementioned, I'm not in favour of scrollbars
background-image: url('http://i.imgur.com/dfzk0TW.png');
}

Javascript Java脚本

$(function () {
  $('#add').on('click', function () {
    $('<p>Text</p>').appendTo('#container');
  });
});

Any suggestions? 有什么建议么? Thank you! 谢谢!

Try this code 试试这个代码

jsfiddle jsfiddle

remove height from css and use below code 从CSS移除高度并使用以下代码

$('<p>Text</p>').appendTo('.container');

remove # and put dot(.) 删除#并放置点(。)

this code will get height of container div and than will add 20px in container div. 此代码将获得容器div的高度,然后将在容器div中添加20px。

  $(function () {
      $('#add').on('click', function () {
        $('<p>Text</p>').appendTo('#container');
        heightWithPx =  $('#container').css('height');
        height = heightWithPx.substr(0,heightWithPx.length-2);
        newHeight = parseFloat(height)+20;
        $('#container').css('height',newHeight+'px');
      });
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM