??
html
<div class="totop" v-show="toTopShow" @click="toTop()">top</div>
css
.totop {
width: 50px;
height: 50px;
line-height: 50px;
border-radius: 25px;
background-color: white;
position: fixed;
bottom: 75px;
right: 10px;
text-align: center;
}
data
data() {
return {
toTopShow: false,
srcoll: 0,
}
},
监听事件
watch: {
srcoll() {
if (this.srcoll > 400) {
this.toTopShow = true;
} else {
this.toTopShow = false;
}
},
},
加载事件
mounted() {
window.addEventListener("scroll", this.srcollShow);
},
methods:
methods: {
srcollShow() {
this.srcoll =
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop;
},
toTop() {
this.toTopSpeed = setInterval(() => {
document.documentElement.scrollTop =
document.documentElement.scrollTop - 20;
//通过改变数字实现动画延迟滚动
if (this.srcoll < 10) {
clearInterval(this.toTopSpeed);
}
}, 1);
},
}
以上操作实现通过监听滚动条>400后,top按钮出现,并且点击top按钮,慢慢回到顶部,低于400隐藏,img以此类推
|