有些时候,在列表中需要用到返回顶部按钮这样的功能,但是ui组件库的自己不喜欢,怎么自己实现一个呢?
html和css的样式结构 看起来非常简单。 下面看看核心的js代码
<template>
<div class="content">
//style样式为动态配置,src为动态配置 这样可以实现图片,样式,大小的自由控制
<img v-show="showTopImg" :style="[myStyle]" @click.stop="backTop"
:src="backIcon" class="backTop"
>
</div>
</template>
//css样式 默认position定位
<style lang="scss" scoped>
.backTop{
position: fixed;
}
</style>
js控制部分,样式由父组件传递下来,没有取默认值
<script>
import icon from '@/assets/icon/backTop.png'
export default {
data() {
return {
showTopImg: false, //控制按钮显示
timer: null,
timerId: null,
scrollTop: 0
}
},
props: {
// 触底显示返回高度,默认2500
backHeight: {
typeof: Number,
default: 2500
},
// 父组件传下来的图片,没有取默认值
backIcon: {
typeof: String,
default: icon
},
// 父组件传下来的样式,必须是对象,没有取默认值
myStyle: {
typeof: Object,
default: () => {
return {
width: '66px',
height: '66px',
right: '10px',
bottom: '68px'
}
}
}
},
mounted() {
//注册监听滚动事件
window.addEventListener('scroll', this.debounce, true)
},
destroyed() {
// 退出时清除监听事件
window.removeEventListener('scroll', this.debounce)
window.clearInterval(this.timerId)
window.clearTimeout(this.timer)
},
methods: {
backTop() {
this.timerId = setInterval(() => {
// 给返回增加动画效果
const speed = Math.floor(-document.documentElement.scrollTop / 5)
document.documentElement.scrollTop = document.documentElement.scrollTop + speed
if (document.documentElement.scrollTop <= 0) {
clearInterval(this.timerId)
}
}, 30)
},
// 防抖函数
debounce(ev) {
if (this.timer) {
clearTimeout(this.timer)
}
this.timer = setTimeout(() => {
// 当滚动的距离大于时出现该按钮
this.scrollTop = window.pageYOffset
this.scrollTop > this.backHeight ?
this.showTopImg = true : this.showTopImg = false
}, 200)
}
}
}
</script>
在父组件中引用
<template>
<div class="content">
//到一定距离显示出来
<backTop :backHeight="2000" :icon="https://xxxx.com" :myStyle="style"/>
</div>
</template>
<script>
import backTop from '@/components/backTop'
export default {
name: 'demo',
components: { backTop },
data() {
return {
style:{
width:"80px",
hieght:"80px",
right:"20px",
bottom:"50px",
background-color:""
{
}
},
created() {},
methods: {}
}
</script>
<style lang="scss" scoped>
</style>