在形目中经常要实现回到顶部的效果,所以我在这做了一个回到顶部的插件。
首先,我们先在这说明一下,实现回到顶部的效果所要满足的要求为:要实现回到顶部效果的盒子必须出现横向滚动条。
子组件如下所示:
原理为监听元素的scroll距离,根据距离判断其滚动距离及滚动速度,和按钮的显示隐藏。
<template> <div> <div class="page-up" @click="scrollToTop" v-show="toTopShow"> <span class="iconfont scrollTop"></span> </div> </div> </template> <script> export default { name: 'scrollTop', data () { return { toTopShow: false } }, mounted () { this.$nextTick(function () { window.addEventListener('scroll', this.handleScroll, true) }) }, destroyed () { window.addEventListener('scroll', this.handleScroll, true) }, methods: { handleScroll () { let dom = document.getElementsByClassName('content')[0] this.scrollTop = dom.scrollTop if (this.scrollTop > 300) { this.toTopShow = true } else { this.toTopShow = false } }, scrollToTop () { let timer = null let _this = this cancelAnimationFrame(timer) timer = requestAnimationFrame(function fn () { if (_this.scrollTop > 5000) { _this.scrollTop -= 1000 document.getElementsByClassName('content')[0].scrollTop = _this.scrollTop timer = requestAnimationFrame(fn) } else if (_this.scrollTop > 1000 && _this.scrollTop <= 5000) { _this.scrollTop -= 500 document.getElementsByClassName('content')[0].scrollTop = _this.scrollTop timer = requestAnimationFrame(fn) } else if (_this.scrollTop > 200 && _this.scrollTop <= 1000) { _this.scrollTop -= 100 document.getElementsByClassName('content')[0].scrollTop = _this.scrollTop timer = requestAnimationFrame(fn) } else if (_this.scrollTop > 50 && _this.scrollTop <= 200) { _this.scrollTop -= 10 document.getElementsByClassName('content')[0].scrollTop = _this.scrollTop timer = requestAnimationFrame(fn) } else if (_this.scrollTop > 0 && _this.scrollTop <= 50) { _this.scrollTop -= 5 document.getElementsByClassName('content')[0].scrollTop = _this.scrollTop timer = requestAnimationFrame(fn) } else { cancelAnimationFrame(timer) _this.toTopShow = false } }) } } } </script> <style scoped> .page-up{ background-color: #F7F7F7; position: fixed; right: 30px; bottom: 55px; width: 40px; height: 40px; line-height: 40px; text-align: center; border-radius: 20px; cursor: pointer; transition: .3s; box-shadow: 0 3px 6px rgba(0, 0, 0, .5); opacity: .5; z-index: 100; } .scrollTop { font-size: 40px; z-index: 10000; } </style>
在这需要说明的是:子组件中的content为滚动的盒子的类名:
组件的使用:
在你所需要的组件中引入即可: