有没有办法使用 Intersection Observers 检测元素是否离开视口(viewport)?例如,我在屏幕上有一个元素,我想在元素顶部到达视口(viewport)顶部时触发回调。来自 MDN:
The Intersection Observer API lets code register a callback function that is executed whenever an element they wish to monitor enters or exits another element (or the viewport), or when the amount by which the two intersect changes by a requested amount. -- (https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API)
因此,如果我执行以下操作,我会认为当元素的顶部也碰到视口(viewport)的顶部时会触发回调?
var options = {
root: document.querySelector('#element'),
rootMargin: '0px',
threshold: 0
}
var observer = new IntersectionObserver(callback, options);
但它似乎只在元素顶部滚动并触及视口(viewport)底部时才被触发,但不是两者兼而有之。想法?
最佳答案
如果我正确理解您要执行的操作,您可以设置 rootMargin
至'0px 0px -100%'
.另外,threshold: 0
是默认值,因此您不需要将其包含在您的选项对象中。
关于javascript - 元素离开视口(viewport)时的交点观察者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53306419/