You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测用户从当前位置滚动100px并移除元素指定类名

问题分析与解决方案

你的问题核心出在滚动事件的判断逻辑上——当前代码是只要窗口滚动距离超过100px就移除类,但你实际需要的是从点击导航链接时的滚动位置出发,滚动100px之后才移除activecopy类。

修改后的完整代码

var scrollvalue = 0;
// 防抖函数,避免scroll事件频繁触发影响性能
function debounce(func, wait) {
  let timeout;
  return function() {
    const context = this;
    const args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(context, args), wait);
  };
}

$('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function() {
  // 记录点击瞬间的滚动位置
  scrollvalue = $(window).scrollTop();
  $(".copyright").addClass("activecopy");
});

// 用防抖包装滚动事件处理函数,减少不必要的DOM操作
$(window).scroll(debounce(function() {
  // 判断当前滚动位置是否比点击时的位置超出了100px
  if ($(window).scrollTop() > scrollvalue + 100) {
    $('.copyright').removeClass('activecopy');
  }
}, 10)); // 10ms的防抖延迟,可根据实际需求调整

关键修改说明

  1. 调整判断基准:把原来固定的100改为scrollvalue + 100,这样就会以点击导航时的滚动位置为起点,滚动满100px后才执行移除类的操作,完全匹配你的需求。
  2. 添加防抖优化:scroll事件在滚动过程中会高频触发,防抖函数可以减少函数执行次数,避免频繁操作DOM导致的页面性能问题。

可选扩展(按需选择)

如果需要实现「类被移除后,即使再次滚动也不再触发判断」的效果,可以在移除类后解绑scroll事件,或者添加一个状态变量控制:

var scrollvalue = 0;
var hasRemovedClass = false;
function debounce(func, wait) { /* 防抖函数保持不变 */ }

$('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function() {
  scrollvalue = $(window).scrollTop();
  $(".copyright").addClass("activecopy");
  hasRemovedClass = false; // 点击时重置状态
});

$(window).scroll(debounce(function() {
  if (!hasRemovedClass && $(window).scrollTop() > scrollvalue + 100) {
    $('.copyright').removeClass('activecopy');
    hasRemovedClass = true;
  }
}, 10));

内容的提问来源于stack exchange,提问作者Santosh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:34:17