Change a div's height to auto using jQuery onc

2019-06-21 05:06发布

问题:

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

回答1:

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


回答2:

You need to bind resize event of the div

$(document).ready(function(){

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

});


回答3:

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


回答4:

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.