Vue实现回到顶部
新建一个Top组件
1 2 <template> 3 <div id="goTop"> 4 <div class="goTop" v-show="goTopShow" @click="goTop"> 5 <i class="el-icon-caret-top goTopIcon"></i> 6 回到顶部 7 </div> 8 </div> 9 </template> 10 <script> 11 export default { 12 name: "goTop", 13 data() { 14 return { 15 scrollTop: "", 16 goTopShow: false 17 }; 18 }, 19 watch: { 20 scrollTop(val) { 21 if (this.scrollTop > 500) { 22 this.goTopShow = true; 23 } else { 24 this.goTopShow = false; 25 } 26 } 27 }, 28 methods: { 29 handleScroll() { 30 this.scrollTop = 31 window.pageYOffset || 32 document.documentElement.scrollTop || 33 document.body.scrollTop; 34 if (this.scrollTop > 500) { 35 this.goTopShow = true; 36 } 37 }, 38 goTop() { 39 let timer = null, 40 _that = this; 41 cancelAnimationFrame(timer); 42 timer = requestAnimationFrame(function fn() { 43 if (_that.scrollTop > 0) { 44 _that.scrollTop -= 250; 45 document.body.scrollTop = document.documentElement.scrollTop = 46 _that.scrollTop; 47 timer = requestAnimationFrame(fn); 48 } else { 49 cancelAnimationFrame(timer); 50 _that.goTopShow = false; 51 } 52 }); 53 } 54 }, 55 mounted() { 56 window.addEventListener("scroll", this.handleScroll); 57 }, 58 destroyed() { 59 window.removeEventListener("scroll", this.handleScroll); 60 } 61 }; 62 </script> 63 64 <style scoped> 65 .goTop { 66 position: fixed; 67 right: 40px; 68 bottom: 60px; 69 width: 40px; 70 height: 40px; 71 border-radius: 50%; 72 background: #fff; 73 padding: 10px; 74 cursor: pointer; 75 box-shadow: 0 0 6px rgba(0, 0, 0, 0.12); 76 } 77 .goTop:hover .goTopIcon { 78 color: rgba(51, 153, 255, 1); 79 } 80 .goTopIcon { 81 font-size: 20px; 82 color: rgba(51, 153, 255, 0.8); 83 } 84 </style> 85 86
在页面中使用(外层高度给高一点)
<div id="app" style="height:2000px"> <Top></Top> </div>
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步