【发布时间】:2021-01-15 22:46:41
【问题描述】:
当观察到的元素有 position: absolute 并且根不是
视口。
我错过了什么吗?
(尝试删除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添加到#intersectionRoot会怎样?这是预期的行为吗? demo -
是的,似乎可以做到。对于 IntersectionObserver 为什么会这样工作,是否有合理的解释?
-
我猜这是因为如果你没有明确地将
position: relative设置为根元素,它的子元素(在本例中为observedElement)指的是body。来自docs: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. -
哦,这很棘手。如果视觉交叉点很重要,就会更容易理解。无论如何,谢谢,如果您将其发布为答案,我会接受。
标签: javascript css-position intersection-observer