html
<template> <a href="javascript:;" class="toTop" @click="backTop" v-show="backToTop"> <i class="iconfont"></i> </a> </template>
js
- 监听滚动事件
利用VUE写一个在控制台打印当前的scrollTop。首先,在 mounted 钩子中给window添加一个滚动滚动监听事件:
mounted() { window.addEventListener("scroll", this.scrollToTop); },
- 监听回到顶部按钮距浏览器顶部的距离,滚动的距离如果大于浏览器高度时,设置 toTop 为true,否则就是false;
scrollToTop() { let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; let browserHeight = window.outerHeight; if (scrollTop > browserHeight) { this.backToTop = true } else { this.backToTop = false } } }
- 点击回到顶部按钮,让距离逐渐减少,形成上划的效果
//回到顶部 backTop() { let back = setInterval(() => { if (document.body.scrollTop || document.documentElement.scrollTop) { document.body.scrollTop -= 100; document.documentElement.scrollTop -= 100; } else { clearInterval(back); } }); },
- 离开该页面需要移除这个监听的事件
destroyed() { window.removeEventListener("scroll", this.scrollToTop); }
css
<style lang="scss"> .toTop { position: fixed; bottom: 150px; right: 30px; z-index: 100; width: 70px; height: 70px; border-radius: 50%; border: 1px solid #999; /*no*/ text-align: center; background-color: #fff; i { color: #999; font-size: 58px; vertical-align: middle; font-weight: 500; } } </style>