纯js监听全局滚动条是否到底了,到底了执行某函数

545 阅读1分钟
export default {
    data () {
        return {
            cb: null
        };
    },
    methods: {
        execScrollBottomFun () {

            //变量scrollTop是滚动条滚动时,距离顶部的距离
            let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;

            //变量windowHeight是可视区的高度
            let windowHeight = document.documentElement.clientHeight || document.body.clientHeight;

            //变量scrollHeight是滚动条的总高度
            let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;

            //滚动条到底部的条件
            if (scrollTop + windowHeight === scrollHeight) {

                // 要执行的回调
                this.cb();
            }
        },
        addCb (cb) {
            this.cb = cb;
            window.addEventListener('scroll', this.execScrollBottomFun);
        },
        removeCb () {
            this.cb = null;
            window.removeEventListener('scroll', this.execScrollBottomFun);
        }
    },
    beforeDestroy () {
        this.removeCb();
    }
};