MDN wants to talk to developers like you: https://qsurvey.mozilla.com/s3/8d22564490d8

Intersection Observer API

这篇翻译不完整。请帮忙从英语翻译这篇文章

这是一个实验中的功能
此功能某些浏览器尚在开发中,请参考浏览器兼容性表格以得到在不同浏览器中适合使用的前缀。由于该功能对应的标准文档可能被重新修订,所以在未来版本的浏览器中该功能的语法和行为可能随之改变。

Intersection observer API提供了一种方法,可以异步观察目标元素的交集变化与祖先元素或顶层文件。

Intersection observer 概念和用法

Intersection observer 允许你配置一个回调函数,称为目标的回调,与之相交视口或称为指定的元素.对于这个API,根元素的目的,通过调用其构造函数并将其传递给回调函数的引用创建路口检查。

var options = {
    root: document.querySelector('#scrollArea'), 
    rootMargin: '0px', 
    threshold: 1.0
}
var callback = function(entries, observer) { 
    /* Content excerpted, show below */ 
};
var observer = new IntersectionObserver(callback, options);

当 threshold 达到 1.0 ,回调函数将会被调用 

为每个观察者配置一个目标

var target = document.querySelector('#listItem');
observer.observe(target);

每当目标满足该IntersectionObserver指定的threshold值,回调被调用。

var callback = function(entries, observer) { 
    entries.forEach(entry => {
        entry.time;               // a DOMHightResTimeStamp indicating when the intersection occurred.
        entry.rootBounds;         // a DOMRectReadOnly for the intersection observer's root.
        entry.boundingClientRect; // a DOMRectReadOnly for the intersection observer's target.
        entry.intersectionRect;   // a DOMRectReadOnly for the visible portion of the intersection observer's target.
        entry.intersectionRatio;  // the number for the ratio of the intersectionRect to the boundingClientRect.
        entry.target;             // the Element whose intersection with the intersection root changed.
    });
};

Interfaces

IntersectionObserver
Provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport. The ancestor or viewport is referred to as the root.
IntersectionObserverEntry
Provides information about the intersection of a particular target with the observers root element at a particular time. Instances of this interface cannot be created, but a list of them is returned by IntersectionObserver.takeRecords().

Specifications

Specification Status Comment
Intersection Observer Editor's Draft Initial definition.

浏览器兼容性

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support

51.0

? ? ? ?
Feature Android Android Webview Firefox Mobile (Gecko) Firefox OS IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support 未实现 51.0 ? ? ? ? ? 51.0

更多参考

文档标签和贡献者

 此页面的贡献者: xrr20160322
 最后编辑者: xrr20160322,