第一次使用vue做项目,UI选择了Element-ui,看到官网有点击回到顶部按钮,并且按钮是在滚动一段距离后才出现的(附带动画),但是官网文档并没有这个组件,于是自己实现了一个。
首先说明,为了使用美化的的滚动条,这里使用了element的隐藏组件 el-scrollbar,所以滚动条滚动不是相对body(document)进行计算了,而是相对于节点 .el-scrollbar>.el-scrollbar__wrap计算的 (这两个类名是组件自动生成的)。
如果要想用 相对于body计算的滚动位置,请看文章最后(只需要修改一下js部分就行了)。
创建ScrollTop.vue组件
模板部分:

js部分

css部分

完整代码在这里,知道这才是你想要的。。(不过还是建议看着敲一遍~)
<template>
<!--transition标签 按钮出现附带动画-->
<transition name="el-fade-in">
<div class="page-component-up" @click="scrollToTop" v-show="toTopShow">
<i class="el-icon-caret-top"></i>
</div>
</transition>
</template>
<script>
export default {
data() {
return {
toTopShow: false,
}
},
methods: {
handleScroll() {
//id scroller-box是自己在组件上添加的,为了方便获取dom
this.scrollTop = document.getElementById("scroller-box").children[0].scrollTop
if (this.scrollTop > 300) {
this.toTopShow = true
}else {
this.toTopShow = false
}
},
scrollToTop() {
let timer = null, _that = this
//动画,使用requestAnimationFrame代替setInterval
cancelAnimationFrame(timer)
timer = requestAnimationFrame(function fn() {
if (_that.scrollTop > 0) {
_that.scrollTop -= 50
document.getElementById("scroller-box").children[0].scrollTop = _that.scrollTop
timer = requestAnimationFrame(fn)
} else {
cancelAnimationFrame(timer)
_that.toTopShow = false
}
})
}
},
mounted() {
//$nextTick 避免dom未加载
this.$nextTick(function () {
let targetScroll = document.getElementById("scroller-box").children[0]
targetScroll.addEventListener('scroll', this.handleScroll)
});
},
destroyed() {
let targetScroll = document.getElementById("scroller-box").children[0]
targetScroll.removeEventListener('scroll', this.handleScroll)
}
}
</script>
<style scoped lang="scss">
.page-component-up{
background-color: #409eff;
position: fixed;
right: 100px;
bottom: 150px;
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>
在app.vue引入ScrollTop组件,大功告成,快去试试吧

最后,这里是没有用到美化滚动条,而是相对于body(document)计算的滚动条
methods: { handleScroll() { //首先修改相对滚动位置 this.scrollTop = this.scrollTop = window.pageYOffset || document.body.scrollTop if (this.scrollTop > 300) { this.toTopShow = true }else { this.toTopShow = false } }, scrollToTop() { let timer = null, _that = this //动画,使用requestAnimationFrame代替setInterval cancelAnimationFrame(timer) timer = requestAnimationFrame(function fn() { if (_that.scrollTop > 0) { _that.scrollTop -= 50 //然后修改这里实现动画滚动效果 document.body.scrollTop = document.documentElement.scrollTop = _that.scrollTop timer = requestAnimationFrame(fn) } else { cancelAnimationFrame(timer); _that.toTopShow = false } }) } }, mounted() { this.$nextTick(function () { //修改事件监听 window.addEventListener('scroll', this.handleScroll) }); }, destroyed() { window.removeEventListener('scroll', this.handleScroll) }
参考资料:https://blog.csdn.net/gmajip1/article/details/80531373