【问题标题】:IntersectionObserver and position: absoluteIntersectionObserver 和位置:绝对
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2014-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多