我正在寻找一种方法来获取去抖动滚动事件的滚动方向。到目前为止,我可以去除卷轴,但是它没有触发我的条件向上/向下脚本。
var el = $(window);
lastY = el.scrollTop();
el.on('scroll', debounce(function(e) {
$('body').bind('DOMMouseScroll', function(e){
if(e.originalEvent.detail > 0) {
//scroll down
scrolldown();
console.log('Down');
}else {
//scroll up
scrollup();
console.log('Up');
}
//prevent page fom scrolling
return false;
});
//IE, Opera, Safari
$('body').bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta < 0) {
//scroll down
scrolldown();
console.log('Down');
}else {
//scroll up
scrollup();
console.log('Up');
}
//prevent page fom scrolling
return false;
});
}, 200));
答案 0 :(得分:1)
无法在此处将事件监听器添加到body
,所以我将其添加到#wrapper
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this,
args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
var onScroll = debounce(function(direction) {
if (direction == false) {
console.log('Scrolling down');
} else {
console.log('Scrolling up');
}
}, 200, true);
$('#wrapper').bind('mousewheel', function(e){
e.preventDefault();
var delta;
if (event.wheelDelta) {
delta = event.wheelDelta;
} else {
delta = -1 * event.deltaY;
}
onScroll(delta >= 0);
});
body {
margin: 0;
padding: 0;
}
#wrapper {
min-height: 100vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="wrapper"><div>