简体   繁体   English

如何使用 Intersection Observer 为不同的目标调用不同的函数?

[英]How to call different functions for different targets using an Intersection Observer?

I'm using the Intersection Observer API on a site.我在网站上使用 Intersection Observer API。 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.您可以为所有不同的目标重用相同的交集观察者和相同的回调,因为回调提供了目标元素,您可以使用该信息来自定义回调的作用。

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:在下面的示例中,我根据重用相同 IntersectionObserver 实例和相同回调函数的不同颜色的div更改屏幕上的消息:

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM