<template>
<div class="scroller-box" id="box">
<transition name="el-fade-in">
<div class="page-component-up" @click="scrollToTop" v-show="toTopShow">
<i class="el-icon-caret-top"></i>
</div>
</transition>
</div>
</template>
<script>
export default {
name: "scroll-to-top",
data() {
return {
toTopShow: false
}
},
mounted() {
//$nextTick 避免dom未加载
this.$nextTick(() => {
window.addEventListener('scroll', this.handleScroll, true)
});
},
destroyed() {
window.removeEventListener('scroll', this.handleScroll)
},
methods: {
handleScroll() {
let scrollTop = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
if (scrollTop > 200) {
this.toTopShow = true
} else {
this.toTopShow = false
}
},
scrollToTop() {
window.pageYOffset = document.body.scrollTop = document.documentElement.scrollTop = 0;
}
},
}
</script>
<style scoped lang="scss">
.page-component-up {
background-color: #FF0000;
opacity: 0.5;
position: fixed;
right: 10px;
bottom: 10px;
width: 40px;
height: 40px;
border-radius: 20px;
cursor: pointer;
transition: .3s;
box-shadow: 0 3px 6px rgba(0, 0, 0, .5);
z-index: 100;
.el-icon-caret-top {
color: #fff;
display: block;
line-height: 40px;
text-align: center;
font-size: 18px;
}
p {
display: none;
text-align: center;
color: #fff;
}
&:hover {
opacity: .8;
}
}
</style>
效果图大致如下