<template>
<van-button v-if="showIcon" id="connectUsImg" class="img_box" @click="backTop()">
<van-icon name="arrow-up" />
</van-button>
</template>
<script>
export default {
name: 'Index',
data() {
return {
showIcon: false
}
},
mounted() {
window.addEventListener('scroll', this.scrollBackTop) // 监听滚动条
},
// 移除滚动条监听
destroyed() {
window.removeEventListener('scroll', this.scrollBackTop)
},
methods: {
backTop() {
const that = this
const timer = setInterval(() => {
const ispeed = Math.floor(-that.scrollTop / 5)
document.documentElement.scrollTop = document.body.scrollTop = that.scrollTop + ispeed
if (that.scrollTop === 0) {
clearInterval(timer)
}
}, 16)
},
scrollBackTop() {
const that = this
console.log('scrollBackTop===1', document.documentElement.scrollTop)
const scrollTop = document.documentElement.scrollTop
that.scrollTop = scrollTop
if (that.scrollTop > 100) {
that.showIcon = true
} else {
that.showIcon = false
}
}
}
}
</script>
<style lang="less" scoped>
.img_box {
width: 68px;
height: 68px;
background-size: 100% 100%;
position: fixed;
z-index: 1000;
right: 60px;
bottom: 164px;
border-radius: 50%;
}
</style>
实现点击置顶功能(以vue为例)
于 2024-05-07 10:58:08 首次发布