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

时间:2022-11-19 13:06:33

I have a div called container which contains dynamically created content(paragraphs) through javascript. The problem is that the paragphs aren't shown on the div once they reach beyond the boundaries of the container. To solve this issue, I tried overflow but that just added x,y scrollbars.

我有一个名为container的div,它包含通过javascript动态创建的内容(段落)。问题是,当滑翔伞超出容器边界时,不会显示在div中。为了解决这个问题,我尝试了溢出,但是只添加了x y滚动条。

What I'm trying to do is increase the height of the container after every parapgraph added i.e. when paragraph is added to container of height 20px, the container increases height to a further 40 px for next paragraph.

我要做的是在每增加一段文字后增加容器的高度,也就是说,当一个段落被添加到高度为20px的容器中时,容器的高度将在下一段增加到40px。

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

Javascript

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

Any suggestions? Thank you!

有什么建议吗?谢谢你!

2 个解决方案

#1


5  

Try this code

试试这个代码

jsfiddle

jsfiddle

remove height from css and use below code

从css中删除高度并使用下面的代码

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

remove # and put dot(.)

删除#并设置点(。)

#2


0  

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');
      });
    });

#1


5  

Try this code

试试这个代码

jsfiddle

jsfiddle

remove height from css and use below code

从css中删除高度并使用下面的代码

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

remove # and put dot(.)

删除#并设置点(。)

#2


0  

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');
      });
    });