我在找这样的东西:
$(window).scroll(function(event){
if (/* magic code*/ ){
// upscroll code
} else {
// downscroll code
}
});
什么好主意吗?
我在找这样的东西:
$(window).scroll(function(event){
if (/* magic code*/ ){
// upscroll code
} else {
// downscroll code
}
});
什么好主意吗?
当前回答
我在这里看到了许多版本的好答案,但似乎有些人有跨浏览器的问题,所以这是我的解决方案。
我已经成功地使用这个方法在FF, IE和Chrome中检测方向…我没有在safari中测试它,因为我通常使用windows。
$("html, body").bind({'mousewheel DOMMouseScroll onmousewheel touchmove scroll':
function(e) {
if (e.target.id == 'el') return;
e.preventDefault();
e.stopPropagation();
//Determine Direction
if (e.originalEvent.wheelDelta && e.originalEvent.wheelDelta >= 0) {
//Up
alert("up");
} else if (e.originalEvent.detail && e.originalEvent.detail <= 0) {
//Up
alert("up");
} else {
//Down
alert("down");
}
}
});
请记住,我也使用这个来停止任何滚动,所以如果你想要滚动仍然发生,你必须删除e.preventDefault();e.stopPropagation ();
其他回答
使用这个来找到滚动方向。这只是为了找到垂直滚动的方向。支持所有跨浏览器。
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");
}
}
例子
我在这里看到了许多版本的好答案,但似乎有些人有跨浏览器的问题,所以这是我的解决方案。
我已经成功地使用这个方法在FF, IE和Chrome中检测方向…我没有在safari中测试它,因为我通常使用windows。
$("html, body").bind({'mousewheel DOMMouseScroll onmousewheel touchmove scroll':
function(e) {
if (e.target.id == 'el') return;
e.preventDefault();
e.stopPropagation();
//Determine Direction
if (e.originalEvent.wheelDelta && e.originalEvent.wheelDelta >= 0) {
//Up
alert("up");
} else if (e.originalEvent.detail && e.originalEvent.detail <= 0) {
//Up
alert("up");
} else {
//Down
alert("down");
}
}
});
请记住,我也使用这个来停止任何滚动,所以如果你想要滚动仍然发生,你必须删除e.preventDefault();e.stopPropagation ();
为什么没有人使用滚动的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属性。
检查当前的scrollTop和之前的scrollTop
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop){
// downscroll code
} else {
// upscroll code
}
lastScrollTop = st;
});
保持超级简单:
jQuery事件监听器
$(window).on('wheel', function(){
whichDirection(event);
});
香草JavaScript事件监听器
if(window.addEventListener){
addEventListener('wheel', whichDirection, false);
} else if (window.attachEvent) {
attachEvent('wheel', whichDirection, false);
}
功能不变:
function whichDirection(event){
console.log(event + ' WheelEvent has all kinds of good stuff to work with');
var scrollDirection = event.deltaY;
if(scrollDirection === 1){
console.log('meet me at the club, going down', scrollDirection);
} else if(scrollDirection === -1) {
console.log('Going up, on a tuesday', scrollDirection);
}
}
我在这里写了一篇更深入的文章