如何检测多个子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>
答案 0 :(得分:1)
不确定,但你试过了吗?
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');}
}
答案 1 :(得分: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');
}
})
&#13;
.parent {
width: 500px;
}
.child {
background-color: green;
width: 700px;
}
&#13;
<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>
&#13;