IntersectionObserver学习和应用

141 阅读2分钟

本文主要参考MDN然后针对IO的每一个参数都进行分析并列举了清晰的例子来帮助理解

最后还有IO的一些用途的具体例子🥸

Preview

参考MDN

The Intersection Observer API 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.

Usages:

  1. Lazy-loading of images or other content as a page is scrolled.

  2. Implementing "infinite scrolling" web sites, where more and more content is loaded and rendered as you scroll, so that the user doesn't have to flip through pages.

  3. Reporting of visibility of advertisements in order to calculate ad revenues.

  4. Deciding whether or not to perform tasks or animation processes based on whether or not the user will see the result.

  • 😁Simple Example

    可以通过下面这个例子快速了解一下IO的使用🧐

Parameters

new IntersectionObserver(callback)
new IntersectionObserver(callback, options)

callback

(entries, observer) => {...}

  • Desc:A function which is called when the percentage of the target element is visible crosses a threshold.

entries

  • Desc:有些时候观察的对象不止一个,因此需要对每个被观察的对象都进行处理。这个 entries 就代表了每一个被观察对象的一些被观察属性 IntersectionObserverEntry - Web APIs | MDN

  • PropertiesIntersectionObserverEntry - Web APIs | MDN 还可以用这里面的很多property来进行callback里面的操作!

  • 一般只观察一个Element的话写作 entries[0] 即可!

  • Codes

observer

  • Desc:回调函数的第二个参数是一个IntersectionObserver对象,表示当前的观察器实例

  • Usages:该对象可以用于一些操作,比如在回调函数内部停止或重新启动观察器,以及更新观察器的配置参数。

  • Codes

options

  • Desc:An optional object which customizes the observer. If options isn't specified, the observer uses the document's viewport as the root, with no margin, and a 0% threshold (meaning that even a one-pixel change is enough to trigger a callback).

root

  • Desc: An Element or Document object which is an ancestor of the intended target, whose bounding rectangle will be considered the viewport. Any part of the target not visible in the visible area of the root is not considered visible.

  • 💣Attention

    1. 如果是指定的root,那么可视区域是content部分不包括padding哦!

    2. Root必须是被观测元素的父元素!

rootMargin

  • Desc:A string which specifies a set of offsets to add to the root's bounding_box when calculating intersections, effectively shrinking or growing the root for calculation purposes. The syntax is approximately the same as that for the CSS margin property

  • Example

  • 💣Attention

thresholds

  • Desc:A list of thresholds, sorted in increasing numeric order, where each threshold is a ratio of intersection area to bounding box area of an observed target. Notifications for a target are generated when any of the thresholds are crossed for that target. If no value was passed to the constructor, 0 is used.

  • Example

  • 💣Attention

  • methods

Usages

LazyLoad

📌只有进入visual viewport的图片才会被加载!

codepen.io/shanxiansen…

Infinite Scrolling

📌滑动到底部自动加载更多内容