一旦 div 达到特定高度,使用 jQuery 将 div 的高度更改为自动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6296793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:39:08  来源:igfitidea点击:

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

jquerycsshtmlheight

提问by Zach

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.

我有一个 div 可以让用户动态添加额外的表单输入。一旦达到某个高度,我希望能够将这个 div 的高度更改为自动。这是我拥有的 jQuery 代码,尽管目前它似乎不起作用。

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

回答by js1568

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

这只会在文档准备好时运行一次。你需要把它放在一个resize()事件处理程序中:

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

回答by Satish

You need to bind resize event of the div

你需要绑定div的resize事件

$(document).ready(function(){

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

});

回答by Matthew Rapati

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.

if 语句只会在文档准备好时运行。如果你想在其他事情发生时做某事(一个事件!),你需要一个事件处理程序。

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

此外,在您的示例中,您将设置widthauto,而不是高度。

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.

但实际上,您不需要 javascript 来执行此操作,您只需在 CSS 中设置最小高度即可。当内容溢出最小高度时,块将拉伸以适应内容,就好像没有设置高度一样。

Example:

例子:

#upload3 {
    min-height: 400px;
}

回答by ShankarSangoli

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.

div的高度什么时候改变?是否有任何事件触发代码以更改此 div 的高度?如果你知道那个事件,那么你应该在那里设置高度。