简体   繁体   English

jQuery:自动调整绝对位置的子div的大小

[英]jquery: auto-size absolute-positioned child div

i'm having the following markup using 2 divs. 我正在使用2 div的以下标记。 the #child div has set position:absolute; #child div已设置位置:绝对;

+------------------------------+
|    +----------+              |
|    | #child   |              |
|    +----------+              |
|                              |
|                              |
|                              |
+------------------------------+

i want to change the child's height by code so that it always auto-sizes to its container like this: 我想通过代码更改孩子的身高,以使其始终自动调整其容器大小,如下所示:

+------------------------------+
|    +----------+              |
|    | #child   |              |
|    |          |              |
|    |          |              |
|    |          |              |
|    +----------+              |
+------------------------------+

is there a default function for it? 有默认功能吗? thx 谢谢

<div id="parent">
  <div id="child"></div>
</div>

with: 与:

#parent { position: relative; background: red; height: 500px; width: 700px; }
#child { position: absolute; background: yellow; height: 80%; top: 10%; bottom: 10; left: 100px; width: 300px; }

Note: the child's height is relative (80%) to the parent's height so no matter what you set the height of the parent to or dynamically resize it to, it'll change the height of the child but the parent must have an explicitly set height (even if its 100%) or this won't work. 注意:孩子的身高是相对于父母的身高的(80%),因此无论您将父母的身高设置为多少或动态调整其大小,它都会更改孩子的身高,但父母必须明确设置孩子的身高高度(即使其为100%),否则将不起作用。

尝试这样的事情(大致近似,根据需要进行调整)

$('#child').css('left', '20%').css('top','10%').css('height','80%').css('width', '30%');

try; 尝试;

$('#child').height($('#child').parent().height());

this assumes that you have no padding and borders on your outer div. 这假设您的外部div没有填充和边框。 if you do you will need to take these off the height in some browsers to ensure it matches. 如果您这样做,则需要在某些浏览器中将这些高度降低,以确保其匹配。

由于您已标记了jQuery,所以我也将为您提供jQuery样式的解决方案:

$("#child").height($("#parent").height()*0.8);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM