原生JS 实现滚屏动画库

293 阅读1分钟

用法

传入需要动画的 Selector ,根据添加的 in-view 和 out-view 来实现自定义滚屏动画

new ScrollMotion('.motion');

核心

/**
 * @param {String} selector 需要动画的元素  选择器
 * @param {number} threshold 是否提前或滞后的阀值,正值:提前threshold像素出现,负值:滞后
 */
 
 var ScrollMotion = function (selector, threshold) {
    var _motionSelf = this;
    this.motionEls = document.querySelectorAll(selector);
    this.threshold = threshold ? threshold : 50;

    function scrollAnimation() {
        _motionSelf.motionEls.forEach(element => {
            if (domInView(element)) {
                element.classList.remove('out-view');
                element.classList.add('in-view');
            } else {
                element.classList.remove('in-view');
                element.classList.add('out-view');
            }
        });
    }

	// 是否在视口内
    function domInView(element) {
        var viewHeight = window.innerHeight || document.documentElement.clientHeight; //可见区域高度
        elementRectTop = element.getBoundingClientRect().top;
        return elementRectTop + _motionSelf.threshold <= viewHeight;
    };

    scrollAnimation();
    window.addEventListener('scroll', scrollAnimation);
}

拓展&优化

  • 对传入的参数进行处理,支持传入 选择器/node/nodeList
// new ScrollMotion(target);
function getMotionElements(target) {
    var elements = [];
    if (typeof target === 'string') {
        elements = [].slice.call(document.querySelectorAll(target), 0);
    } else {
        if (isElement(target)) {
            elements = [target];
        }
        if (target && target.length > 0) {
            elements = [].slice.call(target, 0);
        }
    }
    return elements;
};

function isElement(obj) {
    return !!(obj && obj.nodeType === 1);
};
  • 加入节流函数
  • 设置两个阀值参数(threshold)来进行 进入 和 退出 的时机控制