我在找这样的东西:
$(window).scroll(function(event){
if (/* magic code*/ ){
// upscroll code
} else {
// downscroll code
}
});
什么好主意吗?
我在找这样的东西:
$(window).scroll(function(event){
if (/* magic code*/ ){
// upscroll code
} else {
// downscroll code
}
});
什么好主意吗?
当前回答
在滚动的元素的.data()中存储一个增量,然后就可以测试滚动到达顶部的次数。
其他回答
我在这里看到了许多版本的好答案,但似乎有些人有跨浏览器的问题,所以这是我的解决方案。
我已经成功地使用这个方法在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 ();
我知道已经有了一个公认的答案,但我想张贴我正在使用的,以防它可以帮助任何人。我得到的方向像cliphex与鼠标滚轮事件,但支持Firefox。这样做很有用,以防你在做一些事情,比如锁定滚动,无法获得当前滚动顶部。
点击这里查看现场版本。
$(window).on('mousewheel DOMMouseScroll', function (e) {
var direction = (function () {
var delta = (e.type === 'DOMMouseScroll' ?
e.originalEvent.detail * -40 :
e.originalEvent.wheelDelta);
return delta > 0 ? 0 : 1;
}());
if(direction === 1) {
// scroll down
}
if(direction === 0) {
// scroll up
}
});
对于用户何时从页面顶部滚动以及何时返回到页面顶部,这是简单而容易的检测。
$(window).scroll(function() {
if($(window).scrollTop() > 0) {
// User has scrolled
} else {
// User at top of page
}
});
在元素的.data()中,您可以存储JSON和测试值来启动事件
{ top : 1,
first_top_event: function(){ ...},
second_top_event: function(){ ...},
third_top_event: function(){ ...},
scroll_down_event1: function(){ ...},
scroll_down_event2: function(){ ...}
}
你可以确定鼠标的方向。
$(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');
}
});