Vue点击按钮,回到顶部
作者:互联网
HTML
<div class="footer">
<div class="gotop" v-show="gotop" @click="toTop">Top</div>
</div>
css
.footer .gotop {
text-align: center;
position: fixed;
right: 50px;
bottom: 30px;
cursor: pointer;
padding: 10px;
border-radius: 50%;
background: white;
color: #000000;
}
js
export default {
data() {
return {
gotop: false
};
},
mounted() {
// 此处true需要加上,不加滚动事件可能绑定不成功
window.addEventListener("scroll", this.handleScroll, true);
},
methods: {
handleScroll() {
let scrolltop = document.documentElement.scrollTop || document.body.scrollTop;
scrolltop > 30 ? (this.gotop = true) : (this.gotop = false);
},
toTop() {
let top = document.documentElement.scrollTop || document.body.scrollTop;
// 实现滚动效果
const timeTop = setInterval(() => {
document.body.scrollTop = document.documentElement.scrollTop = top -= 50;
if (top <= 0) {
clearInterval(timeTop);
}
}, 10);
}
}
}
直接回到顶部
// 滚动到app所在的位置(无滚动效果),如app在顶部,即回到顶部
document.getElementById(“app”).scrollIntoView();
标签:body,Vue,top,点击,gotop,按钮,scrollTop,document,app 来源: https://blog.csdn.net/ruantianqing/article/details/112520523