交叉口观察员多次使用

时间:2020-05-20 01:45:50

标签: javascript html css intersection-observer

我熟悉相交观察器,但是我坚持如何将其与具有不同动画效果的不同元素一起使用,请考虑以下内容:

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

那当然是非常重复的,如果我还有另一个元素,我最终将只复制相同的内容而几乎没有变化

所以如何实现更好的解决方案而又不必一遍又一遍地重复自己

1 个答案:

答案 0 :(得分:1)

再次阅读您的问题后,我理解了您想要的内容,并为您制作了此脚本!希望对您有帮助!

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>