简体   繁体   中英

How can I detect if two elements are touching

So I was wondering if you could test for two elements touching each other running a if statement. I know that I am new to javascript and I do not know as much as others, but I couldn't find out how to test for two elements touching.

For example I would want it to be something like this:

var el = document.getElementById("element1");
var el2 = document.getElementById("element2");

if (el1 touching el2) {
//code
//code
}

Yes I know this is not how you do it but I would like to know if there was a certain way you could tell if two elements are touching...

Use Element.getBoundingClientRect() to get their boxes. Then use a collision test, such as AABB , to see if they are intersecting.

Note that I don't think this will work if you apply any crazy rotation transforms to either element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM