Introduction to the Intersection Observer API

Usage Scenarios:

1. Image lazy loading – loading when the image is scrolled to visible 2

Example function: Changes color when an element appears in a visible area

// Add 10000 divs first<div class='list'>
	<div v-for="i in 10000" class='item'>{{i}}</div>
</div>
Copy the code
// Define a method isInViewPort to determine whether the current target is in the viewable area
/ / here getBoundingClientRect method returns the current dom width, height, top, bottom, left, right
function isInViewPort (element) {
  const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  const viewHeight =  window.innerHeight || document.documentElement.clientHeight;
  const { top, right, bottom, left } = element.getBoundingClientRect();
  return top >= 0 && left >= 0 && right <= viewWidth && bottom <= viewHeight;
}
Copy the code
// Get all.items
let itemList = document.getElementsByClassName('item');

// Create the Observer Intersection Observer
// new IntersectionObserver(callBack,options);
// The first argument callback callback method, the second is the corresponding options argument
/* const options = {root:"", specifying the root element, which must be the parent of the current element, not specifying null rootMargin:"", specifying the root element margin, Threshold :"" The value of 1.0 means that the callback will only be executed when the target element is fully present in the root element. If you want the target element to be more than 50% visible in the root element, This can be set to 0.5.} */

const observer = new IntersectionObserver(changeBgHandle,{ threshold: 1.0 });

// Configure a target for each observer
for(let i = 0; i itemList.length; i++){
   observer.observe(itemList[i]);
}

// Whenever the target meets the threshold specified by the IntersectionObserver, the callback is invoked.
function changeBgHandle (elementList) {
  for ( let i = 0; i < elementList.length; i++){
    if(isInViewPort(elementList[i].target)){
       elementList[i].target.style.backgroundColor = "yellow"}}}Copy the code

reference

Developer.mozilla.org/zh-CN/docs/… Developer.mozilla.org/zh-CN/docs/…