当整个元素都在视口中时,交点观察者很容易分辨出来。代码大致是这样的:
// get an element
const thingIWantEntirelyInView = $("#Thing")[0];
const checkInView = new IntersectionObserver((event) => {
console.log("It's in view");
}, {
root: null, // viewport
threshold: 1.0,
});
checkInView.observe(thingIWantEntirelyInView);
不过,我想不通的是如何翻转它,所以它不像包含,更像是覆盖。我想知道我的元素(大于视口)何时完全覆盖屏幕。
我尝试切换null
及thingIWantEntirelyInView
以上的位置,但没有奏效。
我还尝试在页面上添加一个位置固定height: 100vh; width: 100vw
元素并检查与该元素的交集,但似乎交集观察者不适用于两个没有父子关系的元素?也许我做错了代码,但这里有一个例子:
const thingIWantFillingView = document.getElementById("BigScrolly");
const viewPort = document.getElementById("ViewPort");
// what I tried
const checkInView = new IntersectionObserver((event) => {
console.log("This never seems to happen never happen");
}, {
root: thingIWantFillingView,
threshold: 0.5,
});
// when the viewport is at least half inside BigScrolly
checkInView.observe(viewPort);
// example of the thing I don't want
const checkTouchView = new IntersectionObserver((event) => {
console.log("It has touched the viewport");
}, {
root: null,
threshold: 0,
});
// when BigScrolly has touched the viewport
checkTouchView.observe(thingIWantFillingView);
#ViewPort {
position: fixed;
height: 100vh;
width: 100vw;
top: 0px;
left: 0px;
pointer-events: none;
border: 2px solid red;
box-sizing: border-box;
}
#SomePreviousThing {
height: 100vh;
}
#BigScrolly {
height: 300vh;
background: linear-gradient(#FFEEEA, #222);
}
<div id="ViewPort"></div>
<div id="SomePreviousThing">
Ignore this section, scroll down.
</div>
<div id="BigScrolly"></div>
如何使用 Intersection Observers 判断我的元素之一何时完全覆盖屏幕?