IntersectionObserver and position: absolute



IntersectionObserver似乎不工作,当观察到的元素有position: absolute和根不是viewport。

我错过了什么吗?

(尝试删除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。这是一个更新的演示。

如果您没有显式地将position: relative设置为根元素,则它的子元素(在本例中为observedElement)指向body。来自IntersectionObserver文档:An 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.

最新更新