先來一個小小的圖標按鈕bash
<div class="scroll" @click="toTop" v-show="showTop">
<img src="../../assets/images/icon/gotop.png" alt="">
</div>
複製代碼
整體定義基本狀態ui
data () {
return {
scrollTop: 0,
time: 0,
dParams: 20,
scrollState: 0
}
}
複製代碼
監聽當前滾動條的位置this
mounted () {
window.addEventListener('scroll', this.getScrollTop)
}
複製代碼
實現滾動效果spa
methods: {
toTop (e) {
console.log(e)
if (this.scrollState) {
return
}
this.scrollState = 1
e.preventDefault()
let _this = this
console.log(_this.dParams)
this.time = setInterval(function () { _this.gotoTop(_this.scrollTop - _this.dParams) }, 10)
},
gotoTop (distance) {
this.dParams += 20
distance = distance > 0 ? distance : 0
document.documentElement.scrollTop = document.body.scrollTop = window.pageYOffset = distance
if (this.scrollTop < 10) {
clearInterval(this.time)
this.dParams = 20
this.scrollState = 0
}
},
getScrollTop () {
this.scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
}
}
複製代碼
完成~code