<template> <div class="crestBox pointer" @click="crestCick()" v-if="isVisable == true"> 返回 </div> </template> <script> export default{ data() { return { isVisable: false, //控制隐藏按钮 }; }, created() { //添加滚动监听事件 //在窗口滚动时调用监听窗口滚动方法 window.addEventListener('scroll', this.windowScrollListener); }, destroyed() { //离开页面时删除该监听 window.removeEventListener('scroll', this.windowScrollListener) }, //监听窗口滚动 windowScrollListener() { //获取操作元素最顶端到页面顶端的垂直距离 var scrollTop = document.body.scrollTop || document.documentElement.scrollTop; if (scrollTop >= 1500) { this.isVisable = true; //大于1500时显示元素 } if (scrollTop < 1500) { this.isVisable = false; //小于1500时隐藏元素 } }, crestCick() { //让页面滚动回到顶部 window.scrollTo({ top: 0, behavior: 'smooth' }) }, } </script>