javascript - 比较两个元素在 body 中的位置

标签 javascript jquery html css

我有两个元素,即 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/

相关文章:

javascript - 如何更改使用 Grunt 处理 JS 文件的 WordPress 主题?

javascript - 如何定义多个位置 使用 Google Maps API 为循环生成的帖子列表中的每个帖子放置图钉

javascript - 永久解除或关闭 div

javascript - 充满视差滚动的完整背景/边框

javascript - 如何通过javascript使django包含标签中的侧边栏中的元素处于事件状态?

html - GridView 对比HTML 表格 (ASP.net 2.0)

javascript - iFrame 不可编辑(wysiwyg javascript)

javascript - JSON.stringify(array) 返回 []

javascript - JQuery 获取动态值并填充隐藏的表单字段

javascript - mapStateToProps 和变量未定义 React-Redux