有没有办法使用 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
}
});
我试过了,但它阻止了整个功能的工作。我哪里出错了吗?
最佳答案
看:如果scroll是1250px,就已经被>=500
抓到了!
开始测试最高值:1000px!
$(document).scroll(function() {
if ( $(document).scrollTop() >= 1000 ) {
} else if ( $(document).scrollTop() >= 500 ) {
} else {
}
});
编辑1 最好修复您检查的滚动值,而不是在每次if测试一个会发生变化的值时调用它。这取决于你,不是绝对需要:
$(document).scroll(function() {
var value=$(document).scrollTop();/* <== here*/
if ( value >= 1000 ) {
} else if ( value >= 500 ) {
} else {
}
});
编辑2 代码漂亮吗?
$(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*/
});
编辑2 代码可配置?
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*/
});
关于javascript - jQuery,如果窗口滚动了 X 像素,则执行此操作,否则,如果滚动了 XX 像素,则执行其他操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31834158/