Change height on div with javascript

2020-05-10 09:10发布

I want to set the height on a div when the div is more than 100px in height.

For example, when the content of the div makes the div's height fill more than 100px, I want it automatically fit to 200 px.

4条回答
混吃等死
2楼-- · 2020-05-10 09:15

You can try

if($("divID").height() > 100){
    $("divID").css("height","200px");
}
查看更多
唯我独甜
3楼-- · 2020-05-10 09:17

I think that the min-height CSS property is what you are looking for:

div#myDiv {
    min-height: 100px;
    height: auto; 
    display: block; /* float won't work */
}

This should automatically resize your div to wrap its whole content dynamically.

查看更多
劫难
4楼-- · 2020-05-10 09:36

You can just work with min-height and max-height with CSS.

div#myDiv {
min-height: 100px;
height: auto;
max-height: 200px;
}

you could also do something with javascript as said, but with this you can also have the possibility that the height is 150px, or 120px. if you don't want that, You should do it the javascript-way.

查看更多
家丑人穷心不美
5楼-- · 2020-05-10 09:38

One way you can do this is to make sure there is no "height" attribute in the elements CSS (inline styling is fine). Then, when the content is changed call this function:

if ($('#myDiv').height() > 100) {
    // Div is larger than 100px so increase it to 200px
    $('#myDiv').css('height', '200px');
}
查看更多
登录 后发表回答