思路:通过.prevent阻止原生的wheel事件,绑定操控函数,在handleScroll函数中通过event.deltaY判断是向上还是向下滚动,当event.deltaY > 0时表示向下滚动,滚动值加上固定的500值,当event.deltaY < 0时,表示向下滚动,滚动值固定减少500。函数中scrollTop表示距离顶部的高度,通过该值可以控制每次加减500的高度,使用scrollTo()函数进行页面滚动。
注意:此方法如果可以滚动的高度不是500的倍数,会导致滚到到最底部再向上滚不到原来的位置。
<template>
<div
ref="scrollContainer"
@wheel.prevent="handleThrottledScroll"
>
内容区域
</div
</template>
<script>
export default {
methods:{
/**节流 */
throttle (func, limit) {
let timeoutId
let lastExecTime = 0
return function (...args) {
const currentExecTime = Date.now()
const timeSinceLastExec = currentExecTime - lastExecTime
if (!timeoutId && timeSinceLastExec >= limit) {
func.apply(this, args)
lastExecTime = currentExecTime
} else if (!timeoutId) {
timeoutId = setTimeout(() => {
func.apply(this, args)
lastExecTime = Date.now()
timeoutId = null
}, limit - timeSinceLastExec)
}
}
},
/**滚动 */
handleScroll: function (event) {
const scrollContainer = this.$refs.scrollContainer
const delta = 500
const scrollTop = scrollContainer.scrollTop
console.log('可以滚动的高度', scrollContainer.scrollHeight)
let newScrollTop
if (event.deltaY > 0) {
// 向下滚动
newScrollTop = scrollTop + delta
console.log('向下滚动高度', newScrollTop)
} else {
// 向上滚动
newScrollTop = scrollTop - delta
console.log('向上滚动高度', newScrollTop)
}
scrollContainer.scrollTo({
top: newScrollTop,
behavior: 'smooth'
})
},
/**节流滚动 */
handleThrottledScroll: function (event) {
this.throttle(this.handleScroll, 500)(event)
},
}
</script>