我有两个元素,即 canvas 和 div,如下所示。我想知道如何确定 div 是否包含 Canvas 元素(不是根据 DOM 放置,而是根据位置)。
<canvas id="smallBall" style="position: relative; top: 52px; left: -89.0781px;"></canvas>
...
<div class="container">
<div id="hereIGo">The small ball is supposed to be contained in this DIV</div>
</div>
有没有一种方法可以使用 jQuery 实现这一点?
最佳答案
一个选项是使用 getBoundingClientRect()
,它将检索页面上元素的确切位置,与任何相对位置或绝对位置无关。那么比较可能是:
// Both of these are the results of calling getBoundingClientRect() on their respective elements.
var canvas;
var div;
if (div.top >= canvas.top &&
div.left >= canvas.top &&
div.right <= canvas.right &&
div.bottom <= canvas.bottom) {
//the div is inside the canvas.
}
您还有一个 jQuery 选项,它包括调用 $(selector).offset()
。这将返回一个对象,具有与上述接口(interface)类似的接口(interface)。正如您所想象的那样,此解决方案更受支持。
关于javascript - 比较两个元素在 body 中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35286440/