路口观察器多用途

Intersection observer multi usage

我熟悉交集观察器,但是我仍然不知道如何将它与具有不同动画的不同元素一起使用,请考虑以下几点:

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

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

现在假设当 id 为 hero 的 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'))

现在完全没问题,但如果我想观看另一个元素并提供不同的风格怎么办

目前我只是复制相同的代码并更改目标以及我想做的事情

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'))

这当然是非常重复的,如果我有另一个元素,我最终只会复制更多完全相同的元素,并进行少量更改

那么如何在不重复自己的情况下实施更好的解决方案

看了一遍你的问题,我明白了你的意思,我为你制作了这个脚本!希望对您有所帮助!

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>