vue实现返回顶部 电脑版发表于:2023/5/29 16:23 ### 新建一个vue文件goTop.vue ``` <template> <div id="goTop"> <div class="goTop" v-show="goTopShow" @click="goTop"> <!-- <i class="el-icon-caret-top goTopIcon"></i> --> </div> </div> </template> <script> export default { name: "goTop", data() { return { scrollTop: "", goTopShow: false }; }, watch: { scrollTop(val) { if (this.scrollTop > 500) { this.goTopShow = true; } else { this.goTopShow = false; } } }, methods: { handleScroll() { this.scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; if (this.scrollTop > 500) { this.goTopShow = true; } }, goTop() { let timer = null, _that = this; cancelAnimationFrame(timer); timer = requestAnimationFrame(function fn() { if (_that.scrollTop > 0) { _that.scrollTop -= 250; document.body.scrollTop = document.documentElement.scrollTop = _that.scrollTop; timer = requestAnimationFrame(fn); } else { cancelAnimationFrame(timer); _that.goTopShow = false; } }); } }, mounted() { window.addEventListener("scroll", this.handleScroll); }, destroyed() { window.removeEventListener("scroll", this.handleScroll); } }; </script> <style scoped> .goTop { position: fixed; z-index: 98; right: 36px; bottom: 36px; width: 39px; height: 39px; background: transparent; cursor: pointer; background-image: url(~@/assets/imgs/toTop2.png); background-size: cover; /* background-size: 100% 100%; background-repeat: no-repeat; background-position: center center; */ } .goTop:hover .goTopIcon { color: rgba(51, 153, 255, 1); } .goTopIcon { font-size: .2rem; color: rgba(51, 153, 255, 0.8); } </style> ``` ### 使用 引用组件 ``` import goTop from "@/pages/common/goTop"; ``` 使用组件 ``` <goTop></goTop> ``` **返回顶部的图标** 链接: https://pan.baidu.com/s/1BvFjwaTFcjM9wHCqD_mYmQ?pwd=sdrc 提取码: sdrc 复制这段内容后打开百度网盘手机App,操作更方便哦