javascript - 如何以编程方式判断两个绝对定位的元素是否重叠?
问题描述
我认为 DOM API 中没有这样的方法element.doesOverlap(otherElement)
,所以我想我必须手动计算,对吧?不知道有没有捷径。
如果没有,这个方法是什么?似乎有很多方式可以重叠......它会有很多条件。有没有一种简洁的写法?
在伪代码中,我有这个:
if (
((A.top < B.bottom && A.top >= B.top)
|| (A.bottom > B.top && A.bottom <= B.bottom))
&&
((A.left < B.right && A.left >= B.left)
|| (A.right > B.left && A.right <= B.right))) {
// elements A and B do overlap
}
^这是最简单的方法吗?
解决方案
没有更简单的方法。正确的代码是这样的,涵盖了两个元素重叠的所有可能方式:
const doElementsOverlap = (elementA: any, elementB: any) => {
const A = elementA.getBoundingClientRect();
const B = elementB.getBoundingClientRect();
return (
((A.top < B.bottom && A.top >= B.top)
|| (A.bottom > B.top && A.bottom <= B.bottom)
|| (A.bottom >= B.bottom && A.top <= B.top))
&&
((A.left < B.right && A.left >= B.left)
|| (A.right > B.left && A.right <= B.right)
|| (A.left < B.left && A.right > B.right))
);
};
推荐阅读
- mapbox - mapbox gl setFilter 按 indexOf、contains 或 substring 过滤
- python-3.x - 只要输入是数字,就用while循环
- docker - 使用本地 docker 卷持久化 node_modules
- azure-application-insights - 将自定义维度添加到应用程序服务的默认请求遥测的最简单方法是什么?
- css - 为什么长文本换行时 CSS 行高不一样?
- javascript - Nodejs Lambda,.promise() 的目的是什么?
- ruby - 如何在 Ruby 中使用“Ruby 数组外观”编写 yaml 集合?
- visual-studio-code - VSCodeVim:如何更改 vscodevim 命令错误消息的 FG 颜色
- r - 错误:“glmnet_softmax”不是从“命名空间:glmnet”导出的对象
- laravel - Laravel 中 Trait 中的多态关系