<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 0;
}
div {
width: 100px;
height: 100px;
}
#d1 {
background-color: yellow;
}
#d2 {
background-color: blue;
position: absolute;
top: 150px;
}
#d3 {
background-color: red;
}
#d4 {
background-color: green;
position: absolute;
top: 0;
left: 50px;
}
</style>
</head>
<body>
<div id="d1">
<div id="d2"></div>
</div>
<div id="d3">
<div id="d4"></div>
</div>
</body>
<script>
const d1 = document.getElementById("d1");
const d2 = document.getElementById("d2");
const d3 = document.getElementById("d3");
const d4 = document.getElementById("d4");
function isElementOverAnother(el1, el2) {
// How ???
}
isElementOverAnother(d2, d1); // false
isElementOverAnother(d4, d1); // true
isElementOverAnother(d1, d4); // false
isElementOverAnother(d2, d3); // true
isElementOverAnother(d4, d1); // false
</script>
</html>
function isElementOver(el1: HTMLElement, el2: HTMLElement) {
const rect1 = el1.getBoundingClientRect();
const rect2 = el2.getBoundingClientRect();
const left = Math.max(rect1.left, rect2.left);
const top = Math.min(rect2.top, rect1.top);
const right = Math.min(rect2.right, rect1.right);
const bottom = Math.max(rect2.bottom, rect1.bottom);
const width = right - left;
const height = bottom - top;
if (width < 0 || height < 0) {
return false;
}
const el = document.elementFromPoint(left + width / 2, top + height / 2) as HTMLElement;
if (el === el1) {
return true;
} else if (el === el2) {
return false;
} else {
return null;
}
}