Change a div's height to auto using jQuery once the div reaches a certain height

徘徊边缘 提交于 2019-12-10 15:08: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'); }  });

回答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.



来源:https://stackoverflow.com/questions/6296793/change-a-divs-height-to-auto-using-jquery-once-the-div-reaches-a-certain-height

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!