我在找这样的东西:
$(window).scroll(function(event){
if (/* magic code*/ ){
// upscroll code
} else {
// downscroll code
}
});
什么好主意吗?
我在找这样的东西:
$(window).scroll(function(event){
if (/* magic code*/ ){
// upscroll code
} else {
// downscroll code
}
});
什么好主意吗?
当前回答
这段代码在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”的借口是一派胡言。我们必须教育用户。
祝你有愉快的一天。
其他回答
使用这个来找到滚动方向。这只是为了找到垂直滚动的方向。支持所有跨浏览器。
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");
}
}
例子
你可以这样做,而不必跟踪之前的滚动顶部,因为所有其他的例子都要求:
$(window).bind('mousewheel', function(event) {
if (event.originalEvent.wheelDelta >= 0) {
console.log('Scroll up');
}
else {
console.log('Scroll down');
}
});
我不是这方面的专家,所以请随意进一步研究,但当您使用$(element)时。滚动,被监听的事件是一个'滚动'事件。
但是如果您使用bind专门监听鼠标滚轮事件,则回调的事件参数的originalEvent属性包含不同的信息。其中一部分信息是wheelDelta。如果是正数,你就向上移动鼠标滚轮。如果是负的,鼠标滚轮就向下移动了。
我的猜测是鼠标滚轮事件将在鼠标滚轮转动时触发,即使页面没有滚动;在这种情况下,'scroll'事件可能不会被触发。如果需要,可以在回调的底部调用event. preventdefault()来阻止页面滚动,这样就可以将鼠标滚轮事件用于页面滚动之外的其他事情,比如某种类型的缩放功能。
您可以同时使用滚动和鼠标滚轮选项来跟踪上下移动一次。
$('body').bind('scroll mousewheel', function(event) {
if (event.originalEvent.wheelDelta >= 0) {
console.log('moving down');
}
else {
console.log('moving up');
}
});
你也可以用window代替body。
我有弹性滚动的问题(滚动弹跳,橡皮筋)。 如果接近页面顶部,忽略下滚动事件对我来说是有效的。
var position = $(window).scrollTop();
$(window).scroll(function () {
var scroll = $(window).scrollTop();
var downScroll = scroll > position;
var closeToTop = -120 < scroll && scroll < 120;
if (downScroll && !closeToTop) {
// scrolled down and not to close to top (to avoid Ipad elastic scroll-problems)
$('.top-container').slideUp('fast');
$('.main-header').addClass('padding-top');
} else {
// scrolled up
$('.top-container').slideDown('fast');
$('.main-header').removeClass('padding-top');
}
position = scroll;
});
保持超级简单:
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);
}
}
我在这里写了一篇更深入的文章