【问题标题】:JQuery .scroll - How do I retrieve the distance scrolled down OR up the page?JQuery .scroll - 如何检索向下或向上滚动页面的距离?
【发布时间】:2013-05-22 19:34:55
【问题描述】:
我的网页顶部有一个位置固定导航。 Nav 也有一个下拉菜单,它会向下滑动并保持向下直到再次被点击。
我想要实现的是,如果子菜单打开,并且用户决定向下滚动页面,子菜单将自动关闭。
我目前拥有的是:
$(document).scroll(function() {
$(".subMenu").slideUp(300);
});
但是这种方法太敏感了,只需轻轻滚动一下就可以关闭下拉菜单。
理想情况下,我可以在向上或向下滚动 300 像素后让菜单向后滑动,以便有某种“缓冲”空间。
【问题讨论】:
标签:
jquery
scroll
css-position
【解决方案1】:
您可以使用 jquery 的$(window).scrollTop() 来确定当前位置。我创建了一个simple example 来演示它。
var lastFixPos = 0;
var threshold = 200;
$(window).on('scroll', function(){
var diff = Math.abs($(window).scrollTop() - lastFixPos);
if(diff > threshold){
alert('Do something');
lastFixPos = $(window).scrollTop();
}
});
您可以在采取行动之前更改threshold 以提高/降低敏感度。
【解决方案2】:
不用 jQuery,你也可以像这样实现同样的事情:
var winPos = {
y: 0,
yDiff: 0,
moveY: function(diff) {
this.yDiff = -(this.y - diff);
this.y = diff;
}
};
window.onscroll(function(){
var threshold = 10;
winPos.moveY(window.scrollTop);
// Check against position
if (winPos.y > threshold) {
// Do something
}
// Check against difference
if (winPos.yDiff > threshold) {
// Do something
}
});