【问题标题】:How to detect different scrollTop positions如何检测不同的scrollTop位置
【发布时间】:2023-03-14 21:17:01
【问题描述】:

我想检测不同的大于 scrollTop 的位置,如下所示:如果窗口大于 100 像素,我想向 body 添加一个类,如果它再次大于 150,则删除该类并添加另一个类。

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

它仅适用于(如果条件),但不能通过使用(其他条件)处理多个位置。

【问题讨论】:

  • 嗯,150 也大于 100... 也许你应该交换 if 条件?
  • 你能举个例子吗,因为我不太擅长 JS

标签: scrolltop


【解决方案1】:

您的问题是基本控制流,您的第二个条件是多余的,因为如果滚动 >= 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 (...

【讨论】:

  • 现在我更正了代码如下......但没有任何反应。 $(window).scroll(function() { var scroll = $(window).scrollTop(); if (scroll >= 100) { $('body').addClass('one'); } else if (scroll >= 150) { $('body').addClass('two'); $('body').removeClass('one') } });
  • 在最后一行之前重读我的答案。 if..else if 永远不会达到当前状态下的 else if。您需要在>= 100 之前检查>= 150,因为>= 150始终>= 100
猜你喜欢
  • 2017-02-06
  • 1970-01-01
  • 2013-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-16
相关资源
最近更新 更多