向下滚动时控制像素数量

时间:2016-12-12 07:39:57

标签: jquery

我想滚动传递300像素后再发出警告,然后在滚动传递600像素后又发出另一条信息。

但目前只有在我滚动传输300像素时才会发出警报。

这是我的js:

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

希望你能提供帮助。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

您必须使用2个变量hasBeenTriggedAt300hasBeenTriggedAt600 所以,像这样:

 var hasBeenTrigged300 = false;
 var hasBeenTrigged600 = false;

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