【问题标题】:Detect if child divs are wider than parent?检测子div是否比父div宽?
【发布时间】:2016-10-27 12:39:27
【问题描述】:

如何检测多个子 div 是否比其父 div 宽?在这种情况下,当它们更宽时,最右边的会显示在最左边的下方。我曾尝试使用 js 来检查溢出(如这里所述:javascript css check if overflow),但它不起作用。

最终,我想将最右边的 div 保留在其兄弟之下并更改其填充,但仅当它们更宽时。

代码基本上是这样的:

<div class='parent'>
  <span>title</span><br />
  <div class='child'>
    Some content.
  </div>
  <div class='child'>
    More content that sometimes doesn't fit.
  </div>
</div>

【问题讨论】:

  • Divs 总是在彼此之上。它们是块元素。您必须将显示更改为喜欢内联或内联块才能获得这种效果。

标签: javascript html css width detection


【解决方案1】:

这将比较你的 div 的子宽度和父宽度

$('.parent').children('.child').each(function() {
  let $this = $(this);
  console.log($this.width(), '   ', $('.parent').width());
  if ($this.width() > $('.parent').width()) {
    //add the padding you want
    $this.css('padding-top', '10px');
  }
})
.parent {
  width: 500px;
}
.child {
  background-color: green;
  width: 700px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class='parent'>
  <span>title</span>
  <br />
  <div class='child'>
    Some content.
  </div>
  <div class='child'>
    More content that sometimes doesn't fit.
  </div>
</div>

【讨论】:

    【解决方案2】:

    不确定,但你试过吗?

        var children = YourParentDiv.children;
        for (var i = 0; i < children.length; i++) {
           var child_width=children[i].offsetWidth;
           var parent_width = children[i].parentElement.offsetWidth;
           if (child_width>parent_width)
           {console.log('wider');}
        }
    

    【讨论】:

      猜你喜欢
      • 2016-03-20
      • 1970-01-01
      • 2012-12-13
      • 2010-10-29
      • 1970-01-01
      • 2011-07-31
      • 2022-01-05
      • 1970-01-01
      • 2014-09-05
      相关资源
      最近更新 更多