Vue.之.回到顶部
当页面出现上下滚动条时,页面右下角出现回到顶部功能。
在页面上添加如下DIV(写的CSS内部样式),这个DIV功能:出现滚动条往下滑动,就显示出来,反之隐藏。点击DIV快速回到顶部。
<div style="{ height: 60px; 50px; position: fixed; bottom: 35px; right: 15px; background-color: #f2f5f6; box-shadow: 0 0 6px rgba(0,0,0, .12); text-align: center; line-height: 60px; color: #1989fa; cursor: pointer; -webkit-transform: rotate(90deg); -moz-transform: rotate(90deg); -o-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); }" v-if="btnFlag" @click="backTop" > << </div>
在加入EScript代码.
<script> export default { data() { return { btnFlag: false } }, mounted () { window.addEventListener('scroll', this.scrollToTop) }, destroyed () { window.removeEventListener('scroll', this.scrollToTop) }, methods: { // 点击图片回到顶部方法,加计时器是为了过渡顺滑 backTop () { const that = this let timer = setInterval(() => { let ispeed = Math.floor(-that.scrollTop / 5) document.documentElement.scrollTop = document.body.scrollTop = that.scrollTop + ispeed if (that.scrollTop === 0) { clearInterval(timer) } }, 16) }, // 为了计算距离顶部的高度,当高度大于60显示回顶部图标,小于60则隐藏 scrollToTop () { const that = this let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop that.scrollTop = scrollTop if (that.scrollTop > 60) { that.btnFlag = true } else { that.btnFlag = false } } } } </script>
效果图:(滚动条在顶部,div不显示;往下滑动滚动条,div显示)