jQuery,如果窗口滚动了X个像素做这个,否则如果窗口滚动了XX个像素做别的
jQuery, if window has scrolled X pixels do this, else if has scrolled XX pixels do something else
是否有一种方法,使用jQuery,根据窗口滚动的距离做不同的事情?
这是我现在使用的代码;
$(document).scroll(function() {
// If scroll distance is 500px or greated
if ( $(document).scrollTop() >= 500 ) {
// Do something
} else {
// Go back to normal
}
});
我想做的是这样的;
$(document).scroll(function() {
// If scroll distance is 500px or greater
if ( $(document).scrollTop() >= 500 ) {
// Do something
// If scroll distance is 1000px or greater
} else if ( $(document).scrollTop() >= 1000 ) {
// Do something else
} else {
// Go back to normal
}
});
我试过了,但是它阻止了整个函数的工作。我哪里出错了吗?
看:如果滚动是1250px,它已经被>=500
捕获了!
从最高值1000px开始测试
$(document).scroll(function() {
if ( $(document).scrollTop() >= 1000 ) {
} else if ( $(document).scrollTop() >= 500 ) {
} else {
}
});
EDIT1 最好在检查时修复滚动值,而不是每次测试一个可能发生变化的值时调用它。这取决于你,不是绝对需要的:
$(document).scroll(function() {
var value=$(document).scrollTop();/* <== here*/
if ( value >= 1000 ) {
} else if ( value >= 500 ) {
} else {
}
});
EDIT2 代码漂亮吗?
$(document).scroll(function() {
var value=$(document).scrollTop();
if ( value >= 1000 ) { /*do this*/; return;}
if ( value >= 500 ) { /*do this*/; return;}
if ( value >= 150 ) { /*do this*/; return;}
if ( value >= 30 ) { /*do this*/; return;}
/* else */
/*do this*/
});
EDIT2 代码可配置?
var thresholds=[1000, 500, 150];
$(document).scroll(function() {
var value=$(document).scrollTop();
for(int i=0; i<thresholds.length; i++){
if (value >= thresholds[i]) {
/*do this*/; return;
}//end if
}//end for
/* else */
/*do this*/
});
以下几点:
-
重新排序你的条件,从最高的数字开始,否则第二个条件将永远不会被触发。(如果滚动距离是1001px,那么它大于500,将触发第一个条件,从而绕过第二个条件,因为它是
else if
) -
缓存滚动值,这样您就不必在每次条件检查中重新评估它:
$(document).scroll(function() {
var scrollDistance = $(document).scrollTop();
// If scroll distance is 500px or greater
if ( scrollDistance >= 1000 ) {
// Do something else
// If scroll distance is 1000px or greater
} else if ( scrollDistance >= 500 ) {
// Do something
} else {
// Go back to normal
}
});
$(document).scroll(function() {
$top = $(document).scrollTop();
// If scroll distance is 500px or greater
if ($top >= 500 && $top < 1000) {
// Do something
}
// If scroll distance is 1000px or greater
else if ($top >= 1000 && $top < 1500) {
// Do something else
} else {
// Go back to normal
}
});
相关文章:
- javascript mootools平滑滚动'x'像素数量
- JS/CSS:如何在向下滚动超过1200像素(高度)后更改z索引值
- 在用户用动画滚动175像素后缩小固定的Div
- 滚动到..如何滚动到#上方一定数量的像素
- nicewoll mousescrollstep不滚动精确的像素
- 如果滚动 300 像素,请更改背景颜色
- 如何查找可滚动页面的垂直长度(以像素为单位)
- 当您离开页面底部 100 像素时,淡出“滚动到顶部”按钮
- 使用滚动顶部显示滚动的像素
- 带有一些固定像素的垂直滚动条
- j查询窗口滚动事件.每滚动 XX 个像素
- 页脚的动态绝对位置,缺少像素 - 无限滚动
- jQuery滚动事件:如何确定滚动量(滚动增量),以像素为单位
- 在滚动95个像素后,显示固定在页面顶部的Div
- 滚动到锚点上方100像素
- 点击滚动条,需要添加一些像素
- 按子像素滚动网页
- 如何在滚动特定像素后触发css动画
- 正在检测从上到下按钮上的向下滚动像素
- 如何在 CSS 中按行/像素滚动