滚动100个像素后的jQuery警报

用户滚动100像素后是否可以触发警报。

这是我到目前为止所拥有的,但我知道我错过了一些东西;

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

查看窗口.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"); } }); }); 

试试这个:

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

scrollTop()返回一个整数。 滚动超过 100px后,此版本将评估为true,这可能更合适。

尝试

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