首页 > 解决方案 > 使用 Intersection Observer 的不同元素的不同根边距和动画

问题描述

大家好。我有一个我正在开发的网站,并且想要完成不同的滚动动画,例如简单的不透明度和 y 移动动画以及宽度增加动画以及不仅基于视口的自定义根边距。

我完成了我想要的结果,但在我的 html 中留下了三个完整的脚本,如下所示,每个元素我想要拥有自己的根边距和动画。只需使用不同的变量名称等即可使其工作。那么,是否有更有效的方法来缩短代码?

Javascript:

const images = document.querySelectorAll('.tag');

const options = {
  threshold: 0,
  rootMargin: "0% 0% -77% 0%"
};

observer = new IntersectionObserver((images) => {
  images.forEach(entry => {
    if (entry.intersectionRatio > 0) {
      entry.target.style.animation = `tag-anim 1.5s ${entry.target.dataset.delay} forwards cubic-bezier(0.65, 0, 0.35, 1)`;
    }
  })
}, options);

images.forEach(images => {
  observer.observe(images)
});

标签: javascripthtmlanimationscrollintersection-observer

解决方案


推荐阅读