JS 获取指定元素滚动条

  • 获取后台数据接口,当数据无的时候,可以移除滚动监听
    mounted() {
        // 监听滚动
        window.addEventListener("scroll", this.getScroll, true);
    },
        // 瀑布流滚动到底部
        getScroll() {
            // vue 获取元素
            const el = this.$parent.$refs.wrapper;
            // JS 获取元素
            const el = document.querySelector("#wrapper");
            // 滚动条滚动时,距离顶部的距离
            const scrollTop = el.scrollTop || document.body.scrollTop;
            // 可视区的高度
            const windowHeight = el.clientHeight || document.body.clientHeight;
            // 滚动条总高度
            const totalScrollHeight = el.scrollHeight || document.body.scrollHeight;

            if (scrollTop + windowHeight === totalScrollHeight) {
                this.loading = true;
                this.getWaterFall();
            }
        },
        // 瀑布流数据
        getWaterFall() {
            // 加载状态结束
            this.$http
                .get(this.$ApiUrl + "articels?pageIndex=" + this.pageSize)
                .then((res) => {
                    if (res && res.status === 200) {
                        setTimeout(() => {
                            this.loading = false;
                        }, 1000);
                        const data = res.data;
                        this.list = this.list.concat(...data);
                        if (this.pageSize === 1) {
                            for (let i = 0; i < 3; i++) {
                                this.images.push(this.list[i].cover);
                            }
                        }
                        this.pageSize += 1;
                        if (data.length === 0) {
                            window.removeEventListener("scroll", this.getScroll, true);
                        }
                    }
                });
        },
    beforeDestroy() {
        // 移除滚动
        window.removeEventListener("scroll", this.getScroll, true);
    },
posted @ 2022-10-12 11:22  DL·Coder  阅读(1432)  评论(0编辑  收藏  举报