- 绑定滚轮事件,使滚轮滚动时停止页面滚动;同时记录浏览器高度。
data() {
return {
pageHeight: 0,
scrollFLag: true,
}
},
mounted() {
window.addEventListener('mousewheel', this.mousewheelHandler, false)
this.pageHeight = document.documentElement.clientHeight
},
- 滚轮事件中获取滚轮走向,向上滚的话向上翻1页,向下滚的话向下翻1页。代码里加了粘滞,滚动3次时才翻页
mousewheelHandler(e){
e.preventDefault()
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
if(delta > 0){
this.wheelCount -= 1
}else{
this.wheelCount += 1
}
const scroll = document.documentElement.scrollTop
const page = scroll/this.pageHeight + 1
if(this.wheelCount == 3){
this.nextPage(page+1, true)
}else if(this.wheelCount == -3){
this.nextPage(page-1, false)
}
if(this.wheelCount == 3 || this.wheelCount == -3){
this.wheelCount = 0
}
},
- 定义 scrollFLag 防止多次滚动,setTimeout清除flag;setInterval 使他平滑地滚,滚完后清除即可。
nextPage(page, isForward){
if(this.scrollFLag){
this.scrollFLag = false
let scroll = document.documentElement.scrollTop
const p = this.pageHeight*(page-1)
let scrollTimer = setInterval(()=> {
isForward? scroll += navHeight: scroll -= navHeight
if(isForward? scroll > p: scroll < p){
clearInterval(scrollTimer)
}
document.documentElement.scrollTop = isForward? Math.min(scroll, p): Math.max(scroll, p)
}, 20)
setTimeout(()=>this.scrollFLag=true, 1200)
// this.scrollFLag = true
}
},
用元素定位滚动位置会更准确,这里就不改了。小功告成。