如何检测元素是否超出其容器的宽度? [英] How to detect if an element is outside of its container's width?
问题描述
如何检测完全(不是部分)特定容器宽度之外的元素?
How can I detect an element that is completely (not partially) outside of a specific containers width?
例如,我有以下内容:
<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之外,以便将其删除?
My content
div has the width of 100%, and my p
tags are animated to scroll across the screen. How can I detect if they are outside of the content
div so that I can remove them?
由于我的 content
div也有一个容器,因此无法在视口之外进行测试.
Testing for outside of the viewport is not an option since my content
div also has a container.
推荐答案
我相信 getBoundingClientRect()
方法应该可以正常工作.使用这些段落制作了一个更好的工作示例,这是小提琴.
I believe the getBoundingClientRect()
method should work well. Made a better working example using the paragraphs, here's the 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:
Or using jQuery with the same concept:
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"));
更新了我的答案,因为我重读一次,您正在检查孩子是否在父母之外而不是部分地完全.
Updated my answer because I reread that you're checking if the child is completely outside of the parent, not partially.
这篇关于如何检测元素是否超出其容器的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!