vue点击按钮回到顶部实现
效果图
iconfont 哪些图标自己加,这个是要滚动到下面才出现箭头的,最好高度超过 100vh
全部代码
<template> <div class="go-to-top"> <div class="box"> <a href="javascript:void(0);" class="chat"> <i class="iconfont icon-xiaoxi"></i> </a> <a href="javascript:void(0);" class="top" @click="topFunction()" ref="goToTop"> <i class="iconfont icon-31huidaodingbu"></i> </a> <a class="top hidden" @click="topFunction()" ref="goToTopHidden"> <i class="iconfont icon-31huidaodingbu"></i> </a> </div> </div> </template> <script> export default { name: "GoToTop", data(){ return{ topHeight:'', goToTopShow:'', goToTopHidden:'', scrollTopBegin:'', timerId:null, } }, methods:{ topFunction(){ // document.body.scrollTop=0; // document.documentElement.scrollTop=0; console.log(this.scrollTopBegin,'100') this.timerId=setInterval( ()=>{ console.log(this.scrollTopBegin,'200') let begin =this.scrollTopBegin; let target=0; let step=(target-begin)*0.3; begin+=step; if(Math.abs(Math.floor(step))<=1){ clearInterval(this.timerId); window.scrollTo(0,0); console.log(this.scrollTopBegin,'300') return ; } window.scrollTo(0,begin); },20) }, topHeightShow(){ let scrollTopa= window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; this.scrollTopBegin=scrollTopa; if(scrollTopa>=500){ this.goToTopShow.style.display='block'; this.goToTopHidden.style.display='none'; }else { this.goToTopShow.style.display='none'; this.goToTopHidden.style.opacity='block'; } } }, mounted() { this.goToTopShow=this.$refs.goToTop; this.goToTopHidden=this.$refs.goToTopHidden; window.addEventListener('scroll',this.topHeightShow,true); }, beforeDestroy() { window.removeEventListener('scroll',this.topHeightShow,false); } } </script> <style scoped lang="scss"> .go-to-top{ position: fixed; bottom: 100px; right: 40px; transition: all 0.5s; min-height: 110px; .box{ display: flex; flex-direction: column; a{ display: block; width: 50px; height: 50px; border-radius: 4px 4px 0px 0px; text-align: center; } a.chat{ background: #D44A24; i.iconfont{ line-height: 50px; font-size: 30px; color: white; } } a.top{ display: none; background: #CCCCCC; margin-top: 10px; i.iconfont{ line-height: 50px; font-size: 30px; color: white; } } a.top.hidden{ display: none; } } } </style>