首页 > 解决方案 > Intersection Observer 在 600px 视口 (+GSAP) 以下不工作

问题描述

我的内容动画有问题。一切正常,但是当我制作响应式网站并使视口宽度低于 600 像素时,我的交叉点观察器无法正常工作。什么都没发生。

当我滚动我的网站时,我将 console.log 添加到 IO 并且控制台中没有显示任何内容。当我在宽度超过 600 像素时滚动时,我可以在控制台中看到 IO。

也许有人知道这个问题的解决方案?

我的代码:

//global
const slideDuration = 1;

// scroll animation
let target = document.querySelectorAll("section");
const options = {
 root: null,
 threshold: 0,
 rootMargin: "-300px"
};

const contentAnimation = (left, right) => {
  gsap
    .timeline()
    .from(right, { opacity: 0, duration: slideDuration, x: 400 })
    .from(left, { opacity: 0, duration: slideDuration, x: -400 }, "-=0.5");
};

 const io = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
  //show content
  const getElement = entry.target.className;
  const contentElement = document.querySelector(`.${getElement}__content`);
  contentElement.style.opacity = "1";

  //animation
  const right = document.querySelectorAll(`.${entry.target.className}-right`);
  const left = document.querySelectorAll(`.${entry.target.className}-left`);

  contentAnimation(left, right);
  io.unobserve(entry.target);
}
  });
}, options);

target.forEach(section => {
  io.observe(section);
});

标签: javascriptgsapintersection-observer

解决方案


你有rootMargin: "-300px". 这意味着相交不会开始,直到您在任何一侧达到 300 像素。当视口小于 600px 时,没有更多元素可以相交,因此它不起作用。

有关更多信息,请参阅交叉点观察者文档


推荐阅读