IntersectionObserver - 如何判断其中一个元素是否仍在视口中?

时间:2021-06-26 21:59:57

标签: javascript css arrays intersection-observer

我试图制作一个在背景具有特定类时改变颜色的菜单。 我正在使用 Intersection Observers,但它不起作用。基本上我想要这样的东西: 如果(其中一个元素在视图中){ 添加一个类到菜单 } 如果(所有元素不在视图中){ 删除一个类到菜单 }

看看这个代码笔:https://codepen.io/andreas-rasmussen/pen/oNZKJwm

基本上它应该像这个标题一样工作:https://www.eiffelcph.dk

const options = {
  root: null,
  rootMargin: "0px 0px 87% 0px", 
  threshold: 0
};

let callback = (entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      $(".logo").addClass("white");
    } else {
      $(".logo").removeClass("white");
    }
  });

};
let observer = new IntersectionObserver(callback, options);
document.querySelectorAll(".dark-menu").forEach((darkmenu) => {
  observer.observe(darkmenu);
});

1 个答案:

答案 0 :(得分:0)

我们需要记住有多少项目在视图中。您可以通过设置计数来做到这一点,但另一种方法是记住哪些项目在视图中。

此代码段通过设置/删除属性 data-isin 来记住项目是否在视图中。如果任何项目设置了 data-isin,则将徽标类设置为白色。

let callback = (entries, observer) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      entry.target.setAttribute('data-isin', '1');
    } else(entry.target.removeAttribute('data-isin'));
  });
  logo.classList.remove('white');
  for (i = 0; i < divs.length; i++) {
    if (divs[i].getAttribute('data-isin')) {
      logo.classList.add('white');
      break;
    }
  }
};

const observer = new IntersectionObserver(callback);
const divs = document.querySelectorAll('.items div');
const logo = document.querySelector('.logo');

divs.forEach(div => {
  observer.observe(div);
});
body {
  background: pink;
}

.white {
  background: white;
}

.logo {
  width: 10vmin;
  height: 10vmin;
  border-style: solid;
  position: fixed;
  z-index: 1;
}

.items div {
  border-style: solid;
  height: 30vh;
}
<div class="logo"></div>
<div class="items">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>
<div style="height: 200vh; background: cyan; position: relative;">FILLER</div>

相关问题