vue局部div滚动点击回到顶部
针对局部div的内容滚动使用点击回到顶部的需求:
第一步
定义一个超过界面高度的div内容区。并设置id
第二步
点击回到顶部的按钮
// An highlighted block
<template>
<div>
<!-- 点击回到顶部 -->
<div class="gotop" v-show="gotop" @click="toTop"></div>
</div>
</template>
第三步
监听滚动事件
// An highlighted block
data() {
return {
gotop: false,
};
},
mounted(){
// true需要加上,监听滚动
window.addEventListener("scroll", this.handleScroll, true);
},
destroyed() {
//销毁
window.removeEventListener('scroll', this.handleScroll, true)
},
第五步
监听事件的方法
// An highlighted block
methods: {
// 监听滚动事件
handleScroll() {
let scrolltop = document.getElementById("backTop").scrollTop;
scrolltop > 30 ? (this.gotop = true) : (this.gotop = false);
},
// 点击回到顶部
toTop() {
let top = document.getElementById("backTop").scrollTop;
// 定时改变高度,实现滚动效果
const timeTop = setInterval(() => {
document.getElementById("backTop").scrollTop = top -= 30;
if (top <= 0) {
clearInterval(timeTop);
}
}, 10);
},
}
第五步
CSS
// An highlighted block
.gotop {
width: 1rem;
height: 1rem;
text-align: center;
position: fixed;
right: 1rem;
bottom: 1rem;
cursor: pointer;
padding: 10px;
border-radius: 50%;
/* background: red; */
color: #000000;
background-image: url('../../src/assets/Images/top.png');
background-repeat: no-repeat;
background-size: 100% 100%;
}
目前在Google Chrome、Firefox、Microsoft Edge测试都正常,如果没效果,注意id的位置是否正确