javascript - 元素离开视口(viewport)时的交点观察者

标签 javascript intersection-observer

有没有办法使用 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/

相关文章:

javascript - 如何使用 JavaScript 在 x/y 位置绘制点

javascript - 使用所有特殊字符验证字母数字值

javascript - jQuery/Javascript 代码重复

javascript - 在 Internet Explorer 中使用 IntersectionObserver polyfill 延迟加载 img 失败

javascript - IntersectionObserver 无法在 Safari 或 iOS 中工作

javascript - 属性名称为 `undefined`

javascript - 使用javascript从数据库中检索多行并显示在html表格中

javascript - 与 IntersectionObserver API 的行为不一致

javascript - Vue设置IntersectionObserver