![](/img/trans.png)
[英]How to make JavaScript do something every X amount of pixels scrolled
[英]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
}
});
我試過了,但是它使整個功能停止工作。 我在哪里出錯了?
看:如果Scroll為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
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.