使用Intersection Observer API针对不同目标的不同回调 [英] Different callbacks for different targets with Intersection Observer API

查看:163
本文介绍了使用Intersection Observer API针对不同目标的不同回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在网站上使用Intersection Observer API.对于使用它的每个实例,我都使用相同的配置(主视口).我的问题是,触发回调时,我需要发生不同的事情.对于某些人,我想延迟加载图像.对于某些人,我想初始化轮播,等等.

I'm using the Intersection Observer API on a site. For every instance of using it, I'm using the same config (main viewport). My issue is that I need to have different things happen when the callback is fired. For some, I want to lazy load an image. For some, I want to initialize a carousel, etc.

是否可以对所有这些不同的应用程序使用相同的观察者,或者对于每个唯一的回调都必须使用不同的观察者?

Is there a way to use the same observer for all of these different applications or do I have to use a different observer for each unique callback?

推荐答案

您可以为所有不同的目标重用相同的交集观察器和相同的回调,因为回调是目标元素提供的,因此您可以使用该信息来自定义自定义回调.

You can reuse the same intersection observer and same callback for all your different targets, since the callback is provided the target element you can use that information to customize what the callback does.

在下面的示例中,我根据视图中使用哪种颜色不同的div来更改屏幕上的消息,从而重新使用相同的IntersectionObserver实例和相同的回调函数:

In example below I change the message on the screen depending on which differently colored div is in view reusing the same IntersectionObserver instance and same callback function:

const message = document.getElementById('message');

function callbackRouter(entries, observer) {
  let entry = entries[0];
  let target = entry.target;
  if (entry.intersectionRatio > 0) {
    message.textContent = target.classList + " is in view!";
    if (target.dataset.callback) {
      window[target.dataset.callback](target);
    }
  }
}

function lazyLoadImage(target) {
    console.log('lazy load an image here');
}

function initCarousel(target) {
  console.log('initialize a carousel here');
}

function sendAsyncRequest(target) {
  console.log('send an async request here');
}

function doWhatever(target) {
  console.log('literally do whatever you want');
}

const observer = new IntersectionObserver(callbackRouter);
const boxes = document.querySelectorAll('.box');
boxes.forEach(observer.observe.bind(observer));

.box {
  height: 1000px;
}

.violet {
  background-color: violet;
}

.green {
  background-color: green;
}

.tomato {
  background-color: tomato;
}

.orange {
  background-color: orange;
}

#message {
  position: fixed;
  top: 20px;
  left: 20px;
  background-color: white;
  height: auto;
  padding: 10px 20px;
}

<div class="tomato box" data-callback="lazyLoadImage"></div>
<div class="violet box" data-callback="initCarousel"></div>
<div class="orange box" data-callback="sendAsyncRequest"></div>
<div class="green box" data-callback="doWhatever"></div>
<div id="message"></div>

这篇关于使用Intersection Observer API针对不同目标的不同回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆