IntersectionObserver 和位置:绝对

IntersectionObserver and position: absolute

当观察到的元素有 position: absolute 而根不是时,IntersectionObserver 似乎不起作用 视口。

我是不是遗漏了什么?

(尝试删除 position: absolute 以查看预期结果。)

let intersectionRoot = document.getElementById("intersectionRoot");
let observedElement = document.getElementById("observedElement");
let shifted = false; // Internal for the example

let interSectionObserver = new IntersectionObserver(
    (entries, observer) => {
        console.log(entries[0].isIntersecting)
    },
    { root: intersectionRoot }
);
interSectionObserver.observe(observedElement);

window.setInterval(
    () => {
        observedElement.classList.toggle("shifted")
    },
    1000
)
#intersectionRoot {
    background-color: red;
    width: 100px;
    height: 100px;
}

#observedElement {
    position: absolute;
    background-color: green;
    width: 50px;
    height: 50px;
}

.shifted {
    transform: translate3d(110px, 0, 0)
}
<div id="intersectionRoot">
    <div id="observedElement" draggable="true"></div>
</div>

解决方案是将position: relative添加到根元素。这是更新后的 demo.

如果您没有明确地将 position: relative 设置为根元素,则其子元素(在本例中为 observedElement)指的是 body。来自 IntersectionObserver docsAn IntersectionObserver with a non-null root is referred to as an explicit root observer, and it can observe any target Element that is a descendant of the root in the containing block chain.