2012-02-21 34 views
14

用戶滾動100像素後是否可以觸發警報?滾動100像素後的jQuery警報

這是我到目前爲止,但我知道我失去了一些東西;

$(window).scroll(function() { 
    if (document.documentElement.clientHeight + 
     $(document).scrollTop() == "100px") 
    { 
     alert("You've scrolled 100 pixels."); 
    } 
}); 
+0

這是什麼代碼的結果? – 2012-02-21 09:30:04

回答

40

看窗口.scrollTop(返回一個整數):

$(window).scroll(function() { 
    if ($(this).scrollTop() === 100) { // this refers to window 
     alert("You've scrolled 100 pixels."); 
    } 
}); 

,但如果你已經滾動102px它不會觸發警報框。

,如果你只是想觸發警報一旦有一個全局變量,如果它已經被觸發,設置爲true:

$(function(){ 
    var hasBeenTrigged = false; 
    $(window).scroll(function() { 
     if ($(this).scrollTop() >= 100 && !hasBeenTrigged) { // if scroll is greater/equal then 100 and hasBeenTrigged is set to false. 
      alert("You've scrolled 100 pixels."); 
      hasBeenTrigged = true; 
     } 
    }); 
}); 

或只是取消綁定滾動事件一次警告框已經被觸發:

$(function(){ 
    $(window).bind("scroll.alert", function() { 
     var $this = $(this); 
     if ($this.scrollTop() >= 100) { 
      alert("You've scrolled 100 pixels."); 
      $this.unbind("scroll.alert"); 
     } 
    }); 
}); 
+0

使用$(this).scrollTop()> = 100會更好嗎? – whostolemyhat 2012-02-21 09:31:48

+0

取決於,如果他只是希望它被觸發的確切數量,那麼它的正確。我編輯過,並添加了另一個例子。 – voigtan 2012-02-21 09:32:51

+0

你可以使用jQuery的[one()](http://api.jquery.com/one/)函數,該函數在第一次調用後自動解除事件綁定 – yoavmatchulsky 2012-02-21 09:37:15

0

試試這個:

$(document).scrollTop() >= 100) { 
    // ... 
} 

scrollTop()返回一個整數。一旦您滾動過去 100px,此版本將評估爲true,這可能更合適。

0

嘗試

document.documentElement.clientHeight + $(document).scrollTop() == 100