vue2.0_在vue中实现移动端返回顶部操作
前言
需要在移动端实现,滚动到下面的时候,点击回到顶部的操作。下面的代码有些注意事项。我实现的是点击顶部的横条,返回顶部(类似苹果系统的操作)
HTML部分
<div class="box">
<div class="scrollTop" @click="backTop" v-if="scrollType">top</div>
</div>
css部分
.box {
position: relative;
.scrollTop {
width: 35px;
height: 35px;
position: fixed;
background-color: rgba(255, 255, 255,.7);
border-radius: 50%;
text-align: center;
line-height: 35px;
bottom: 65px;
right: 20px;
z-index: 1002;
border: 1px solid #000;
}
}
js部分
data() {
return {
scrollType: false,
};
},
mounted() {
window.addEventListener("scroll", this.handleScroll, true); // 这里的true一定要写
},
// 离开这个页面销毁滚动条事件,不然会给每一个页面都触发
beforeDestroy() {
window.removeEventListener("scroll", this.handleScroll, true);// 这里的true一定要写
},
methods:{
// 回到顶部
backTop() {
document.documentElement.scrollTop = 0;
},
/*如果不想让按钮在一开始的时候存在,而是在滚动了一定的距离的时候再出现,那设置 一个滚动条的监听*/
handleScroll(e) {
let scrollTop = document.documentElement.scrollTop;
if (scrollTop > 100) {
this.scrollType = true;
} else {
this.scrollType = false;
}
},
}
会遇到的问题:
window.removeEventListener("scroll", this.handleScroll, true);
这里不加true,没有效果- 写完之后没有效果? 刷新一下,让页面重新加载!