2015-09-18 51 views
1

我想要检测我是否正在滚动,但仅在滚动距离当前位置一定距离后。当我停止滚动,这个距离复位到当前位置在浏览器中从当前位置滚动距离后检测滚动

我知道如何检测滚动过去的.scrollTop()页面上的某一点,但我想这一定点是我目前的位置,但我已经停止之后才滚动。

为什么我需要这个:我有一个导航栏,它改变了所有的CSS取决于如果我已经向上或向下滚动。因此,如果我的滚动手指以不同的方向发抖(例如从上到下滚动),则导航栏将像频闪灯那样转换。所以我的计划是只检测10px以上的滚动条,所以用户需要制作一个专门的滚动条来激活导航栏的CSS变化。

伪代码:

if (scrolled 10px above or below current_location in browser) { 
    console.log('it worked'); 
} else { 
    console.log('You have not scrolled far enough!') 
} 

if (scrolling stops) { 
    reset position of current_location. 
} 
+0

为什么这会得到downvoted? :-( –

回答

2

这将是最简单的方法:

$(document).ready(function() { 

var previous = 0; 

$(window).scroll(function() { 

    var current = $(this).scrollTop(); 

    if (current > previous) // down 
    else // up 

    previous = current; 
}); 
}); 

http://codepen.io/anon/pen/ojxPOg?editors=001

使用鼠标滚轮插件,您甚至在实际开始滚动方向之前就会知道。可能会很好,但对于移动,上述仍然是需要的(以最快的方式)。

http://codepen.io/anon/pen/YPmjym?editors=001

编辑 - 在触摸设备上如预期的第一个代码可能无法正常工作。平移屏幕实际上并不会触发滚动,直到您释放它为止(据我所见)。解决这个问题需要另一个脚本来监听touchmove事件。以下是一个示例:

$(window).on('touchstart', function(e) { 

    var swipe = e.originalEvent.touches, 
    start = swipe[0].pageY; 

    $(this).on('touchmove', function(e) { 

     var contact = e.originalEvent.touches, 
     end = contact[0].pageY, 
     distance = end-start; 

     if (distance < -30) // up 
     if (distance > 30) // down 
    }) 
    .one('touchend', function() { 

     $(this).off('touchmove touchend'); 
    }); 
}); 

约30像素的数量通常被视为目标滑动。

1

我不明白你为什么需要这个,但低于为您的伪代码的代码:

var currentScrolled = 0; 
$(document).scroll(function() { 

currentScrolled = $(this).scrollTop(); 

if (currentScrolled > 10) { 
    console.log('it worked'); 
} else { 
    console.log('You have not scrolled far enough!') 
}}); 

$(document).scrollstop(function(){ 
    currentScrolled = 0; 
}); 
+0

我有一个导航栏可以改变它的所有CSS,具体取决于我是否向上或向下滚动,所以如果我的滚动手指在不同的方向上抖动(例如从上到下滚动),导航栏会像所以我的计划是只检测10px或以下的滚动条,所以用户需要制作一个专用的滚动条来激活导航栏的CSS变化。 –

+0

我不认为'scrollstop()'是一种标准方法。 – Shikkediel

2
with this i was able to get the swipe up and down... 

我添加了一个标志,以便它只有一次是解决继续滑动的问题上运行。 感谢https://css-tricks.com/forums/topic/detect-vertical-direction-of-jquery-touchmove/

currentY: 
var swipe = false, 
var lastY, 
timer; 
$(document).bind('touchstart', function(e) { 

lastY = e.originalEvent.touches ? e.originalEvent.touches[0].pageY : e.pageY; 
console.log(lastY); 
}); 
$(document).bind('touchmove mousemove', function(e) { 

var currentY = e.originalEvent.touches ? e.originalEvent.touches[0].pageY : e.pageY; 

if(!swipe){ 
if (Math.abs(currentY-lastY) < 50) { return; } 
swipe = true; 
if (currentY > lastY) { 
console.log('down'); 
} else { 
console.log('up'); 
} 
} 
}).on('touchend', function(){ 
    swipe = false; 
});