吸顶操作

<div class='head-wrap'></div>
<div class='head'></div>
export default class head {
     
    constructor() {
     
        this.init();
    }

    throttle (func, delay) {
     
        var prev = Date.now();
        var first = true;
        return function() {
     
            var now = Date.now();
            if (first) {
     
                func.apply(this, arguments);
                first = false;
                return
            }
            if (now - prev >= delay) {
     
                func.apply(this, arguments)
                prev = Date.now();
            }
        }
    }

    handleClass(top) {
     
        if (top < 0) {
     
            $('.head').addClass('active');
        } else {
     
            $('.head').removeClass('active');
        }
    }

    handleScroll = () => {
     
        if (!!IntersectionObserver) {
     
            let observer = new IntersectionObserver(() => {
     
            	// 需要监听上级元素
                const top = $('.head-wrap')[0].getBoundingClientRect().top;
                this.handleClass(top);
            }, {
     
                threshold: [1]
            });
            observer.observe($('.head-wrap')[0]);
        } else {
     
            window.addEventListener('scroll', this.throttle(() => {
     
                const top = $('.head-wrap')[0].getBoundingClientRect().top;
                this.handleClass(top);
            }, 10));
        }
    }

    init() {
     
        this.handleScroll();
    }
};

你可能感兴趣的:(javascript,js)