首页 > 解决方案 > 仅在视口中进行动画处理

问题描述

我正在尝试采用以下技术:

https://codepen.io/donovanh/pen/rmzNZJ

到一个学习项目,但我不确定我做错了什么。我在这里上传了我自己项目的部分内容:

https://codepen.io/cucurutcho/pen/KKWRrov

基本上,当元素在屏幕上可见时,JS 正在努力向元素添加自定义类,因此对其进行一些动画处理。但是在我的示例中,没有添加类,我不知道为什么,我可能在这里遗漏了一些超级简单的东西,但是任何可以阐明的人都非常感谢!为了更容易,在我的代码笔(第二个)上,您可以看到具有“滚动显示”类的元素不像在第一个代码笔上那样工作,我从中获得了技术。这是应该执行此操作的 JS 代码:

    // Detect request animation frame
var scroll = window.requestAnimationFrame ||
             // IE Fallback
             function(callback){ window.setTimeout(callback, 1000/60)};
var elementsToShow = document.querySelectorAll('.show-on-scroll'); 

function loop() {

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

    scroll(loop);
}

// Call the loop for the first time
loop();

// Helper function from: http://stackoverflow.com/a/7557433/274826
function isElementInViewport(el) {
  // special bonus for those using jQuery
  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))
  );
}

标签: javascripthtmljquerycssfrontend

解决方案


推荐阅读