У меня есть следующий код IntersectionObserver, который работает как триггер прокрутки для анимации на сайте, и все работает нормально.
Однако я хотел бы переключить метод forEach(), который работает как вызов IntersectionObserver, на цикл for, но я не могу заставить его работать.
Я уверен, что это можно сделать, но это сводит меня с ума.
Причина в том, что я использую полифилл, чтобы IntersectionObserver работал в старых версиях IE и Edge, но, конечно, метод forEach() не работает в этих браузерах.
Я прокомментировал свою попытку цикла в нижней части кода.
Любая помощь была бы потрясающей.
Codepen: 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>
forEach
или преобразоватьbox
в массив. - person SamVK   schedule 06.08.2018