思路
利用onmousewheel实现
原理
onmousewheel事件,每滚动一次,就会触发一次。不像onscroll,不停的触发。
实现
this.$nextTick(() => {
// 滚动方向,-1向下滚; 1向上滚
let scrollDirection = -1
// 计数,滚动了多少次
let index = 0
// 上次的scrollTop
let lastScrollTop = 0
this.$refs.tableBody.onmousewheel = (e) => {
if (e.wheelDelta) {
if (e.wheelDelta > 0) {
//当鼠标滚轮向上滚动时
scrollDirection = 1
}
if (e.wheelDelta < 0) {
//当鼠标滚轮向下滚动时
scrollDirection = -1
}
} else if (e.detail) {
if (e.detail < 0) {
//当鼠标滚轮向上滚动时
scrollDirection = 1
}
if (e.detail > 0) {
//当鼠标滚轮向下滚动时
scrollDirection = -1
}
}
// 当滚动的距离大于等于滚动的高度减去滚动div自身的高度,且是向下滚动时,就要return出去
// index==0,且是向上滚动时,也要return出去
if (
(this.$refs.tableBody.scrollTop >=
this.$refs.tableBody.scrollHeight -
this.$refs.tableBody.offsetHeight &&
scrollDirection == -1) ||
(scrollDirection == 1 && index == 0)
) {
return
}
if (scrollDirection == 1) {
// 鼠标向上滚
index--
} else {
index++
}
document.getElementsByClassName('table-body')[0].scrollTop = 50 * index
lastScrollTop = 50 * index
}
this.$refs.tableBody.onscroll = (e) => {
// 通过onscroll,禁止自己滚动,必须通过我们来赋值scrollTop才能动
if (!lastScrollTop) {
lastScrollTop = e.target.scrollTop
} else {
e.target.scrollTop = lastScrollTop
}
}
})
嗯,代码还可以优化下。我就不优化了,正忙着写bug。。。。。。。。