首页 > 解决方案 > 如何更改我的代码以使项目在滚动一次后保持可见?

问题描述

如何更改我的代码以使项目在滚动一次后保持可见?我是一个真正的编码初学者,所以欢迎任何帮助和提示。提前谢谢你的帮助!

.inline-photo {
  opacity: 0;
  transform: translateY(60px) ;
  transition: transform 3000ms 500ms cubic-bezier(0,1,.3,1),
              opacity 300ms 500ms ease-out;
  will-change: transform, opacity;
}

.inline-photo.is-visible {
  opacity: 1;
  transform: rotateZ(0deg);
}

var scroll = window.requestAnimationFrame ||
            function(callback){ window.setTimeout(callback, 1000/60)};

            var elementsToShow = document.querySelectorAll('.show-on-scroll');

            function loop() {

  elementsToShow.forEach(function (element) {
    if (isElementInViewport(element)) {
      element.classList.add('is-visible');
    } else {
      element.classList.remove('is-visible');
    }
  });

  scroll(loop);
}

loop();

function isElementInViewport(el) {

  if (typeof jQuery === "function" && el instanceof jQuery) {
    el = el[0];
  }
  var rect = el.getBoundingClientRect();
  return (
    (rect.top <= 0
      && rect.bottom >= 0)
    ||
    (rect.bottom >= (window.innerHeight || document.documentElement.clientHeight) &&
      rect.top <= (window.innerHeight || document.documentElement.clientHeight))
    ||
    (rect.top >= 0 &&
      rect.bottom <= (window.innerHeight || document.documentElement.clientHeight))
  );
}

我的最终目标是在它们出现一次后让其保持可见。

标签: javascriptcssanimation

解决方案


在 CSS 中将逻辑与设备分开。

创建一个应用可见性的类。

.inline-photo.is-shown {
  opacity: 1;
  transform: rotateZ(0deg);
}

并让is-visible管理代码中的状态。

if (isElementInViewport(element)) {
  element.classList.add('is-visible', 'is-shown');
} else {
  element.classList.remove('is-visible');
}

推荐阅读