Vue中实现回到顶部的功能
参考:https://www.cnblogs.com/wangRong-smile/articles/11880249.html
回到顶部的DOM部分:
<div class="back_top" @mouseover="enterBackTop" // 鼠标进入回到顶部图标的背景颜色变深 @mouseout="outBackTop" // 鼠标移开,背景颜色变浅 ref="backTop" :style="{ opacity: opacity }" v-show="gotop" @click="handleScrollTop" > <span class="iconfont icon-backtotop"></span> </div>
script部分:
props: ['ele'], // 这个是接收父组件传递过来的值 data() { return { opacity: '.3', gotop: false, scrollHeight: 100, scrollTop: 0 }; },
mounted() { window.addEventListener('scroll', this.handleScroll, true); // 注册滚动事件 },
methods: { enterBackTop() { this.opacity = '1'; }, outBackTop() { this.opacity = '0.3'; }, handleScroll(e) { const that = this; const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; that.scrollTop = scrollTop; that.scrollTop > this.scrollHeight ? (this.gotop = true) : (this.gotop = false); }, handleScrollTop() { // this.$nextTick(() => { // this.ele.scrollIntoView({ behavior: 'smooth' }); // }); const that = this; const timer = setInterval(() => { const ispeed = Math.floor(-that.scrollTop / 5); document.documentElement.scrollTop = document.body.scrollTop = that.scrollTop + ispeed; if (that.scrollTop === 0) { clearInterval(timer); } }, 16); } }
记录自己的采坑之路,需要时方便查找