如何检测不同的 scrollTop 位置

How to detect different scrollTop positions

我想检测不同的大于 scrollTop 的位置,如下所示:如果 window 大于 100px,我想在正文中添加一个 class,如果它再次大于 150,则删除 class 并添加另一个 class.

$(window).scroll(function() {    
   var scroll = $(window).scrollTop();
   if (scroll >= 100)  {
      $('body').addClass('one');
   }
   else (scroll >= 150)  {
      $('body').addClass('two');
      $('body').removeClass('one')
   }
});

它只适用于应用(if 条件)但不能通过使用(else 条件)处理多个位置。

你的问题是基本的控制流,你的第二个条件是多余的,因为如果滚动 >= 150 那么它肯定 >= 100 这意味着你永远不会到达第二个块:

if (scroll >= 100) {
    // execute if scroll is greater or equal to 100
} else if (scroll >= 150) {
    // execute if scroll is NOT greater or equal to 100
    // execute if scroll is greater or equal to 150
}

你需要像这样交换它们:

if (scroll >= 150) {
    // execute if scroll is greater or equal to 150
} else if (scroll >= 100) {
    // execute if scroll is NOT greater or equal to 150
    // execute if scroll is greater or equal to 100
}

你这里也有语法错误:else (scroll >= 150) { 应该是 else if (...