我在找这样的东西:
$(window).scroll(function(event){
if (/* magic code*/ ){
// upscroll code
} else {
// downscroll code
}
});
什么好主意吗?
我在找这样的东西:
$(window).scroll(function(event){
if (/* magic code*/ ){
// upscroll code
} else {
// downscroll code
}
});
什么好主意吗?
当前回答
你可以确定鼠标的方向。
$(window).on('mousewheel DOMMouseScroll', function (e) {
var delta = e.originalEvent.wheelDelta ?
e.originalEvent.wheelDelta : -e.originalEvent.detail;
if (delta >= 0) {
console.log('scroll up');
} else {
console.log('scroll down');
}
});
其他回答
检查当前的scrollTop和之前的scrollTop
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop){
// downscroll code
} else {
// upscroll code
}
lastScrollTop = st;
});
这是在用户结束滚动时检测方向的最佳解决方案。
var currentScrollTop = 0 ;
$(window).bind('scroll', function () {
scrollTop = $(this).scrollTop();
clearTimeout($.data(this, 'scrollTimer'));
$.data(this, 'scrollTimer', setTimeout(function() {
if(scrollTop > currentScrollTop){
// downscroll code
$('.mfb-component--bl').addClass('mfbHide');
}else{
// upscroll code
$('.mfb-component--bl').removeClass('mfbHide');
}
currentScrollTop = scrollTop;
}, 250));
});
为什么没有人使用滚动的jQuery返回的事件对象?
$window.on('scroll', function (event) {
console.group('Scroll');
console.info('Scroll event:', event);
console.info('Position:', this.pageYOffset);
console.info('Direction:', event.originalEvent.dir); // Here is the direction
console.groupEnd();
});
我使用铬,我没有检查其他浏览器,如果他们有dir属性。
使用这个来找到滚动方向。这只是为了找到垂直滚动的方向。支持所有跨浏览器。
var scrollableElement = document.getElementById('scrollableElement');
scrollableElement.addEventListener('wheel', findScrollDirectionOtherBrowsers);
function findScrollDirectionOtherBrowsers(event){
var delta;
if (event.wheelDelta){
delta = event.wheelDelta;
}else{
delta = -1 * event.deltaY;
}
if (delta < 0){
console.log("DOWN");
}else if (delta > 0){
console.log("UP");
}
}
例子
存储之前的滚动位置,然后查看新的滚动位置是否大于或小于该位置。
这里有一个避免任何全局变量的方法(在这里可以找到):
(function () {
var previousScroll = 0;
$(window).scroll(function(){
var currentScroll = $(this).scrollTop();
if (currentScroll > previousScroll){
alert('down');
} else {
alert('up');
}
previousScroll = currentScroll;
});
}()); //run this anonymous function immediately