如何检测可滚动div的滚动方向,来自OnScroll事件?我想向scrollTop添加15,如果用户向上滚动并减去15,如果用户向下滚动。是否可以不使用JQuery?
答案 0 :(得分:2)
/**
* Calculate incremental amounts of pixels scrolled in each axis.
* Value is signed to its direction.
*/
function incrementalScroll(e) {
var scrollX = (this.x || window.pageXOffset) - window.pageXOffset;
var scrollY = (this.y || window.pageYOffset) - window.pageYOffset;
this.x = window.pageXOffset;
this.y = window.pageYOffset;
test(scrollX, scrollY);
}
window.onscroll = incrementalScroll;
根据需要使用它。
function test(scrollX, scrollY){
var directionX = !scrollX ? "NONE" : scrollX>0 ? "LEFT" : "RIGHT";
var directionY = !scrollY ? "NONE" : scrollY>0 ? "UP" : "DOWN";
console.log(directionX, scrollX, directionY, scrollY);
}
答案 1 :(得分:0)
我能想到的最简单的方法如下。如果您可以将let oldScroll
包装到闭合中以使其更整洁,那就很好了,但这不是必须的。
const scrollableEle = document.getElementById('scrollable-ele')
let oldScroll = scrollableEle.scrollTop
scrollableEle.addEventListener('scroll', doSomething)
function doSomething(e) {
contentRight.scrollTop > oldScroll ? /* down */ : /* up */
oldScroll = scrollableEle.scrollTop
}