Change a div's height to auto using jQuery onc

2019-06-21 04:49发布

I have a div that lets the user add additional form inputs dynamically. I'd like to be able to change this div's height to auto once it reaches a certain height. Here is the jQuery code I have, though it doesn't seem to be working at the moment.

$(document).ready(function(){
if($('#upload3').height() > 400){ $('#upload3').css('width','auto'); }  });

4条回答
beautiful°
2楼-- · 2019-06-21 04:54

This will only run ONCE when the document is ready. You need to put it inside a resize() event handler:

$('#upload3').resize(function() {
  if($(this).height() > 400){ $(this).css('height','auto'); }  });
});
查看更多
Rolldiameter
3楼-- · 2019-06-21 05:12

You need to bind resize event of the div

$(document).ready(function(){

$("#upload3").bind("resize", function() {
   if($('#upload3').height() > 400){ $('#upload3').css('width','auto'); }
});

});
查看更多
一纸荒年 Trace。
4楼-- · 2019-06-21 05:16

When is the height of a div changing? Is there any event that triggers to code to change the height of this div? If you know that event then you should set the height there.

查看更多
神经病院院长
5楼-- · 2019-06-21 05:18

That if statement is only going to run when the document is ready. If you want to do something when something else happens (an event!), you need an event handler.

Also, in your example, you're setting the width to auto, not the height.

But really, you don't need javascript to do this, you can simply set a minimum height in CSS. When the content overflows the minimum height, the block will stretch to fit the content as if there was no height set.

Example:

#upload3 {
    min-height: 400px;
}
查看更多
登录 后发表回答