简体   繁体   English

交叉口观察者多用途

[英]Intersection observer multi usage

I'm familiar with the intersection observer, however i'm stuck on how to use it with different elements that has different animations consider the following:我熟悉交叉点观察器,但是我坚持如何将它与具有不同动画的不同元素一起使用,请考虑以下几点:

<div id="hero">
  <h1>hello world<h1>
</div>

<div class="nav">
  <li>nav item</li>
  <li>nav item</li>
  <li>nav item</li>
</div>

now let's say when the div with id of hero comes to view port move it to the left现在让我们说当具有 hero id 的 div 来查看端口时将其移到左侧

const io = new IntersectionObserver((entries, observer) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        const hero = entry.target
        hero.style.transform = 'translateX(30px)'
        observer.unobserve(target)
      }
    })
  })
  io.observe(document.querySelector('#hero'))

now that's totally fine but what if i want to watch another element and give different style现在这完全没问题,但是如果我想看另一个元素并给出不同的风格怎么办

currently i'm just copying the same code and changing the target and what i would like to do like so目前我只是复制相同的代码并更改目标以及我想做的事情

const io2 = new IntersectionObserver((entries, observer) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        const hero = entry.target
        hero.style.opacity = 0;
        observer.unobserve(target)
      }
    })
  })
  io.observe(document.querySelector('.nav'))

that's of course very repetitive, and if i have another element i would end up just copying the same exact more with few changes这当然是非常重复的,如果我有另一个元素,我最终只会复制更多相同的元素,只需进行少量更改

so how to implement a better solution without repeating myself over and over那么如何在不一遍又一遍地重复自己的情况下实施更好的解决方案

after I read your question again I understood what you want, and I made this script for you!在我再次阅读您的问题后,我明白了您想要什么,我为您制作了这个脚本! hope it helps!希望能帮助到你!

 const Observe = (target, onIntersection)=>{ const io = new IntersectionObserver((entries, observer) => { entries.forEach((entry) => { if (entry.isIntersecting) { if( onIntersection && typeof onIntersection == "function" ){ onIntersection(entry); observer.unobserve(target); } } }); }); io.observe(target); }
 <div id="hero"> <h1>hello world<h1> </div> <div class="nav"> <li>nav item</li> <li>nav item</li> <li>nav item</li> </div> <script> document.addEventListener("DOMContentLoaded", ()=>{ Observe( document.querySelector("#hero"), function(entry){ const hero = entry.target; hero.style.transform = 'translateX(30px)'; } ); Observe( document.querySelector(".nav"), function(entry){ const hero = entry.target hero.style.opacity = 0; } ); }); </script>

Thank you for everything for the code too strong it unlocked my problem !!!感谢您为代码太强大而解决了我的问题所做的一切!

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

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