vue滚动回到顶部事件

2021-04-07  本文已影响0人  有你才精彩XX
export default {
        name: "side",
        data(){
            return{
                gotop: false,
                timer:null
            }
        },
        mounted() {
            // 此处true需要加上,不加滚动事件可能绑定不成功
            window.addEventListener("scroll", this.handleScroll, true);
        },
        destroyed() {
            window.removeEventListener('scroll', this.handleScroll); //离开页面需要移除这个监听的事件
            clearInterval(this.timer);
        },
        methods: {
            handleScroll() {
                let scrolltop = document.documentElement.scrollTop || document.body.scrollTop;
                scrolltop > 30 ? (this.gotop = true) : (this.gotop = false);
            },
            toTop() {
                let top = document.documentElement.scrollTop || document.body.scrollTop;
                // 实现滚动效果
                this.timer = setInterval(() => {
                    document.body.scrollTop = document.documentElement.scrollTop = top -= 50;
                    if (top <= 0) {
                        clearInterval(this.timer);
                    }
                }, 10);
            }
        }
    }
上一篇 下一篇

猜你喜欢

热点阅读