如何检查元素是否与其他元素重叠? [英] How to check if an element is overlapping other elements?

查看:176
本文介绍了如何检查元素是否与其他元素重叠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个div元素。每个都有450px的宽度和高度。如何检查第一个div是否与第二个div重叠?

I have two div elements. Each of them have 450px width and height. How do I check if the first div is overlapping the second div?

我尝试使用javascript hittest,但它有点复杂。由于我想知道它是如何工作的,我想开始使用更简单的代码。

I've tried to use javascript hittest, but it's a little bit complicated. Since I'm trying to find out how it actually work, I would like to get started with a simpler code.

我发现我可以使用。 getClientRects 来获取元素的边界,但我不确定如何比较边界。

I found out that I can use .getClientRects to get the boundary of an element, but I'm not exactly sure how to compare boundaries.

请告诉我!

推荐答案

rect1 rect2 通过 getBoundingClientRect()检索:

var overlap = !(rect1.right < rect2.left || 
                rect1.left > rect2.right || 
                rect1.bottom < rect2.top || 
                rect1.top > rect2.bottom)

解释:如果括号中的一个或多个表达式是 true ,则没有重叠。如果所有都是 false ,则必须有重叠。

Explain: if one or more expressions in the parenthese are true, there's no overlapping. If all are false, there must be an overlapping.

这篇关于如何检查元素是否与其他元素重叠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆