如何检测完全(不是部分)超出特定容器宽度的元素?
例如,我有以下内容:
<div id="content">
<div class="wrapper">
<p>This is a paragraph</p>
<p>This is a paragraph</p>
<p>This is a paragraph</p>
<p>This is a paragraph</p>
</div>
</div>
我的 content
div 的宽度为 100%,我的 p
标签是动画的,可以在屏幕上滚动。我如何检测它们是否在 content
div 之外,以便我可以删除它们?
因为我的 content
div 也有一个容器,所以无法在视口(viewport)之外进行测试。
最佳答案
我相信 getBoundingClientRect()
方法应该运行良好。使用段落制作了一个更好的工作示例,这里是 fiddle .
function HorizontallyBound(parentDiv, childDiv) {
var parentRect = parentDiv.getBoundingClientRect();
var childRect = childDiv.getBoundingClientRect();
return parentRect.left >= childRect.right || parentRect.right <= childRect.left;
}
var bound = HorizontallyBound(document.getElementById("parent"), document.getElementById("some_paragraph"));
或者使用具有相同概念的 jQuery:
function HorizontallyBound($parentDiv, $childDiv) {
var parentRect = $parentDiv[0].getBoundingClientRect();
var childRect = $childDiv[0].getBoundingClientRect();
return parentRect.left >= childRect.right || parentRect.right <= childRect.left;
}
var bound = HorizontallyBound($("#parent"), $("#some_paragraph"));
更新了我的答案,因为我重读了您正在检查 child 是否完全在 parent 之外,而不是部分。
关于javascript - 如何检测元素是否超出其容器的宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22829188/