我在找这样的东西:
$(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');
}
});
其他回答
对于用户何时从页面顶部滚动以及何时返回到页面顶部,这是简单而容易的检测。
$(window).scroll(function() {
if($(window).scrollTop() > 0) {
// User has scrolled
} else {
// User at top of page
}
});
为了忽略页面顶部和底部的任何snap / momentum / bounce back,这里是Josiah接受的答案的修改版本:
var prevScrollTop = 0;
$(window).scroll(function(event){
var scrollTop = $(this).scrollTop();
if ( scrollTop < 0 ) {
scrollTop = 0;
}
if ( scrollTop > $('body').height() - $(window).height() ) {
scrollTop = $('body').height() - $(window).height();
}
if (scrollTop >= prevScrollTop && scrollTop) {
// scrolling down
} else {
// scrolling up
}
prevScrollTop = scrollTop;
});
这段代码在IE, Firefox, Opera和Chrome中工作良好:
$(window).bind('wheel mousewheel', function(event) {
if (event.originalEvent.deltaY >= 0) {
console.log('Scroll down');
}
else {
console.log('Scroll up');
}
});
'wheel mousewheel'和属性delay必须在bind()函数中使用。
记住:出于安全考虑,你的用户必须更新他们的系统和浏览器。2018年,“我有ie7”的借口是一派胡言。我们必须教育用户。
祝你有愉快的一天。
在元素的.data()中,您可以存储JSON和测试值来启动事件
{ top : 1,
first_top_event: function(){ ...},
second_top_event: function(){ ...},
third_top_event: function(){ ...},
scroll_down_event1: function(){ ...},
scroll_down_event2: function(){ ...}
}
我在这里看到了许多版本的好答案,但似乎有些人有跨浏览器的问题,所以这是我的解决方案。
我已经成功地使用这个方法在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 ();