<div class="scrolltop" @click="toTop()" v-show="scrollshow">
</div>
let timer = null //全局属性,可以写到data里
data() {
return {
scrollshow: false,
step:{ //此数据是控制动画快慢的
type:Number,
default:1000
}
}
},
created() {
let vm =this;
window.onscroll=function(){
if (document.documentElement.scrollTop>600) {
vm.scrollshow=true; //超过下滑超过600,展示置顶按钮
}else {
vm.scrollshow=false;
}
}
},
toTop(){ // 置顶包括动画
timer = setInterval(function () {
let osTop = document.documentElement.scrollTop || document.body.scrollTop
let ispeed = Math.floor(-osTop / 5)
document.documentElement.scrollTop = document.body.scrollTop = osTop + ispeed
this.isTop = true
if (osTop == 0) {
clearInterval(timer)
}
},30)
},
//滚动到相应位置
scrollTo(num) {
window.scrollTo({
top: num,
left: 0,
});
},
在vue组件中添加返回顶部按钮,下滑超过600时,展示这个按钮,点击置顶