javascript - 将 forEach() 方法更改为 For 循环以与 IntersectionObserver 一起使用 - Javascript

标签 javascript for-loop foreach intersection-observer

我有以下 IntersectionObserver 代码,它用作网站上动画的滚动触发器,一切正常。

但是,我想将调用 IntersectionObserver 的 forEach() 方法切换为 for 循环,但我无法让它工作。

我确信这是可以做到的,但这让我有点疯狂。

想要这个的原因是因为我使用了一个polyfill,以便IntersectionObserver可以在旧版本的IE和Edge中工作,但当然forEach()方法在这些浏览器中不起作用。

我已经在代码底部的循环中注释掉了我的尝试。

任何帮助都会很棒。

代码笔: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>

最佳答案

您有一个观察者,但您正在对其应用索引。当您迭代这些框时,您的索引访问器应该位于框上。

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

这应该可以工作,但尚未经过测试。

关于javascript - 将 forEach() 方法更改为 For 循环以与 IntersectionObserver 一起使用 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51711977/

相关文章:

javascript - 如果 URL 包含此字符串,则隐藏具有此类/id 的所有 div(循环脚本)

javascript - 触发模糊事件而不是点击

javascript - 关于node.js回调中的 'this'

javascript - 如何在 Internet Explorer 8 中使用 new Image()?

嵌套 for 循环内的 continue 语句

html - 在knockout js中查找foreach data-bind的最后一次迭代

javascript - 我需要在 Meteor 中生成一个随机数

python - 从一个列表中查找另一个列表中的字符串对象

php - 针对预定义的数字运行 while 循环(以执行查询)

java - 为什么可以使用增强的 for 循环更改字段变量但不能初始化对象?