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

求助:基于滚动位置为Div添加四类状态的jQuery代码问题

嘿,我来帮你搞定这个滚动方向的问题!你之前的代码应该是没记录上一次的滚动位置,所以没法判断用户是向上还是向下滚动。咱们来调整一下代码,把滚动方向的逻辑补全,同时保证顶部、底部的状态优先级更高:

修正后的完整代码

// 存储上一次的滚动位置,初始值设为页面顶部
let lastScrollTop = 0;
// 替换成你要操作的目标div的选择器
const targetElement = $('.your-target-div');

// 用on()替代bind()(bind()在jQuery 3.0+已被废弃)
$(window).on('scroll', function() {
    const currentScroll = $(this).scrollTop();
    const windowHeight = $(this).innerHeight();
    const totalDocumentHeight = $(document).height();

    // 先移除所有状态类,避免多个类叠加导致样式冲突
    targetElement.removeClass('at-top at-bottom scrolling-down scrolling-up');

    // 1. 判断是否处于页面顶部
    if (currentScroll === 0) {
        targetElement.addClass('at-top');
    }
    // 2. 判断是否处于页面底部
    else if (currentScroll + windowHeight >= totalDocumentHeight) {
        targetElement.addClass('at-bottom');
    }
    // 3. 判断滚动方向
    else {
        // 向下滚动:当前滚动位置 > 上一次滚动位置
        if (currentScroll > lastScrollTop) {
            targetElement.addClass('scrolling-down');
        }
        // 向上滚动:当前滚动位置 < 上一次滚动位置
        else {
            targetElement.addClass('scrolling-up');
        }
    }

    // 更新上一次的滚动位置,供下一次滚动判断使用
    lastScrollTop = currentScroll;
});

关键说明

  • 记录上一次滚动位置:新增lastScrollTop变量,每次滚动后更新,用来和当前滚动位置对比,判断方向。
  • 优先处理极端状态:顶部和底部是特殊位置,所以优先判断这两种情况,避免滚动方向类和极端状态类冲突。
  • 移除旧类再添加新类:每次滚动时先移除所有相关类,防止多个状态类同时存在,保证样式只对应当前状态。
  • 替换废弃方法:用on()替代bind(),因为bind()在jQuery 3.0及以上版本已经被废弃,on()是更推荐的事件绑定方式。

记得把代码里的$('.your-target-div')替换成你实际要操作的div选择器,同时确保你的CSS里已经定义了at-top、at-bottom、scrolling-down、scrolling-up这四个类的样式哦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:10:31