Vue中實現回到頂部的功能
阿新 • • 發佈:2020-07-16
參考: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); } }