简体   繁体   English

如何为包含多个绝对div的相对定位的div设置动态高度

[英]how to set dynamic height for a relative positioned div which contains multiple absolute div

I have to set auto height for relative positioned div which contains multiple absolute position div's inside it. 我必须为相对位置的div设置自动高度,该位置在其中包含多个绝对位置div。 Without mentioning height to the outer div positioned relative the content inside the absolute div is not visible due to overflow:hidden property. 在不提及相对于外部div定位的高度的情况下,由于overflow:hidden属性,绝对div内的内容不可见。

Is there any Javascript to make this possible.. If so please advise me. 有没有任何Javascript可以实现这一目标。如果是,请告诉我。

Thanks in advance. 提前致谢。

Since absolute positioned children does not affect parents size, you should calculate the bounds of parent div manually. 由于绝对定位的子代不会影响父代的大小,因此您应该手动计算父代div的范围。 For instance to get height of the parent you should iterate over child elements and find maximum value of child's top plus height, and to get width you should find maximum left plus width pair. 例如,要获取父对象的高度,您应该遍历子元素并找到孩子的顶部和身高的最大值,要获取宽度,您应该找到最大左数和宽度对。 You can use the following function to adjust parent's width an height: 您可以使用以下功能来调整父母的宽度和高度:

function setSize() {
  var i, count,
      maxWidth = 0,
      maxHeight = 0,
      top, left, width, height,
      parent = document.getElementById('parent');

  for(i=0,count=parent.childNodes.length;i<count;i++) {
    if(parent.childNodes[i].nodeType === 1) {
      top = parent.childNodes[i].offsetTop;
      left = parent.childNodes[i].offsetLeft;
      width = parent.childNodes[i].offsetWidth;
      height = parent.childNodes[i].offsetHeight;
      if(top + height > maxHeight) {
        maxHeight = top + height;
      }
      if(left + width > maxWidth) {
        maxWidth = left + width;
      }
    }
  }
  parent.style.width = maxWidth + 'px';
  parent.style.height = maxHeight + 'px';
}

the function assumes that you parent div have an id="parent" 该函数假定您的父div具有id="parent"

Working example you can find here: http://jsbin.com/ifelur/1/edit 您可以在这里找到工作示例: http : //jsbin.com/ifelur/1/edit

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

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