Как определить, какой из элементов на странице находится сверху?

Собственно, вопрос. Есть два элемента в DOM, могут находиться в абсолютно разных местах, иметь любые стили (position, zIndex и т.д.). Как определить какой из элементов отрисован по Z-оси выше?

Ссылки:
https://www.w3.org/TR/css-position-3/#painting-order
https://developer.mozilla.org/en-US/docs/Learn/CSS...
https://developer.mozilla.org/en-US/docs/Web/CSS/C...
https://habr.com/en/post/166435/

<!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>
  • Вопрос задан
  • 805 просмотров
Решения вопроса 1
arvitaly
@arvitaly Автор вопроса
В общем, правильный вариант сложный, требует учитывать много деталей (подробнее по ссылкам из вопроса).
Для двух элементов можно воспользоваться функцией document.elementFromPoint.

Как то так:
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;
    }
}
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы