Modificare un metodo forEach () in un ciclo For da utilizzare con IntersectionObserver-Javascript


Ho il seguente codice IntersectionObserver che funziona come trigger di scorrimento per le animazioni su un sito che funziona tutto BENE.

Tuttavia, vorrei passare il metodo forEach() che funziona come chiamata per IntersectionObserver a un ciclo for, ma non riesco a farlo funzionare.

Sono sicuro che questo può essere fatto, ma mi sta facendo impazzire un po'.

La ragione per volere questo è perché sto usando un polyfill in modo che IntersectionObserver funzioni nelle versioni precedenti di IE e Edge, ma ovviamente il metodo forEach () non funziona in questi browser.

Ho commentato il mio tentativo di loop nella parte inferiore del codice.

Qualsiasi aiuto sarebbe fantastico.

Codice: https://codepen.io/emilychews/pen/xJaZay

window.addEventListener("load", function(){
  
var iO = "IntersectionObserver" in window; /* true if supported */
var box = document.querySelectorAll('.box');
  
if (iO) {
  const config = {
    root: null, // sets the framing element to the viewport
    rootMargin: '0px',
    threshold: .5
  };
    
  let observer = new IntersectionObserver(function(entries) {
    entries.forEach(function(item) {
      
      if (item.intersectionRatio > .5) {
        
        item.target.classList.add("active");

      } else {
        item.target.classList.remove("active");
      }
      
    });
    
  }, config);

  box.forEach(function(item){
    observer.observe(item);
  });

  // for (i = 0; i < box.length; i++) {
  // observer[i].observe(item);
  // }
  
} // end of if(iO)
  
}); // end of load event
body {
  font-family: arial;
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 280vh;
}

.box {
  position: relative;
  margin: 1rem 0;
  width: 100px;
  height: 100px;
  background: blue;
  opacity: 1;
  transition: .5s all;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
}

#box1{
  margin-bottom: 100px;
}

.active {
  background: red;
  opacity: 1;
}
<div id="box1" class="box">Box 1</div>
<div id="box2" class="box">Box 2</div>
Author: The Chewy, 2018-08-06

1 answers

Hai un osservatore ma stai applicando un indice su di esso. Mentre stai iterando sulle caselle, il tuo accessor indice dovrebbe essere sulla casella.

for (i = 0; i < box.length; i++) {
    observer.observe(box[i]);
}

Questo dovrebbe funzionare, non è testato però.

 2
Author: Phil Cooper, 2018-08-06 16:33:10