javascript JS:滚动以触发动画

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript JS:滚动以触发动画相关的知识,希望对你有一定的参考价值。

import offset from './getOffset';

//Ref: https://envato.com/blog/triggering-css-animations-scroll/

export default function() {

    let windowHeightPlusPadding = window.outerHeight * .8;
    let scrolled = document.documentElement.scrollTop || document.body.scrollTop;
    let targets = document.querySelectorAll('[data-animation]:not(.animated)');

    [].forEach.call(targets, function(elem){

      let offsetTop = offset(elem).top;

      if (scrolled + windowHeightPlusPadding > offsetTop) {
        if (elem.hasAttribute('data-timeout')) {
          window.setTimeout(function() {
            if(-1 == elem.className.indexOf('animated'))
              elem.className = elem.className + ' animated ' + elem.dataset.animation
          }, parseInt(elem.dataset.timeout) );
        } else {
          if(-1 == elem.className.indexOf('animated'))
            elem.className = elem.className + ' animated ' + elem.dataset.animation
        }
      }
    });

}
import revealOffset from './util/reavealOffset'

//Run on Page Refresh
revealOffset();

//Run on Scroll
window.onscroll = revealOffset();
//Ref: https://plainjs.com/javascript/styles/get-the-position-of-an-element-relative-to-the-document-24/

export default function(element) {

  var rect = element.getBoundingClientRect(),
  scrollLeft = window.pageXOffset || document.documentElement.scrollLeft,
  scrollTop = window.pageYOffset || document.documentElement.scrollTop;
  return { top: rect.top + scrollTop, left: rect.left + scrollLeft }

}

以上是关于javascript JS:滚动以触发动画的主要内容,如果未能解决你的问题,请参考以下文章

javascript 在滚动触发器上错开动画

JavaScript实现页面滚动到div区域div以动画方式出现

用wow.js实现页面滚动时触发animate.css动画特效

通过滚动触发CSS关键帧动画

javascript 动画滚动到纯JS中的目标

在 JavaScript 中触发 CSS 动画