<template>
<div>
<el-main id="el-main">正文部分...</el-main>
<!-- 点击回到顶部按钮 -->
<div class="scrollTop" @click="clickBackTop" v-show="scrollTopCount > 50"><i class="el-icon-top"></i></div>
</div>
</template>
<script>
export default {
data() {
return {
scrollTopCount: 0, // 监听#el-main滚动距离顶部的高度
}
},
methods: {
// 点击回到顶部
clickBackTop(){
const box = document.getElementById('el-main')
var timer = '';
timer = setInterval(() => {
this.scrollTopCount = Math.floor(this.scrollTopCount / 20);
box.scrollTop=this.scrollTopCount;
if(this.scrollTopCount == 0){
clearInterval(timer);
}
}, 100);
}
},
mounted() {
// 监听元素滚动
var that = this;
const box = document.getElementById('el-main')
box.addEventListener('scroll', (e => {
var scrollTop = e.target.scrollTop;
that.scrollTopCount = scrollTop;
}))
}
}
</script>
<style>
.scrollTop{
width: 50px;
height: 50px;
border-radius: 50%;
text-align: center;
line-height: 50px;
border: 1px solid #ddd;
background: #ccc;
position: fixed;
right: 30px;
bottom: 100px;
}
</style>
vue(js)监听元素滚动,并实现点击返回顶部效果
于 2023-02-24 11:42:49 首次发布