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

jQuery滚动事件忽略>=1280px宽度判断条件始终生效问题

问题根因

现有代码宽度判断失效的核心原因有3个:

  • 每次checkWidth执行且视口宽度≥1280px时,都会重复给window绑定新的scroll事件,且已绑定的scroll事件不会被解绑,后续哪怕窗口宽度降到1280px以下,之前绑定的滚动逻辑依然会持续运行
  • scroll事件回调内部没有做宽度校验,只要事件被绑定过,无论当前视口宽度是多少都会执行头部样式修改逻辑
  • 外层已经包裹了$(document).ready,内部重复嵌套的$(document).ready会直接立即执行,没有实际控制作用反而打乱逻辑执行顺序
修复方案
  • 仅在DOM就绪时绑定一次scroll事件,把宽度判断逻辑移到scroll回调内部,每次滚动先校验视口宽度,不满足≥1280px的条件直接终止逻辑
  • resize事件触发时增加小屏样式重置逻辑,避免窗口从大屏缩到小屏后,头部残留大屏交互的修改样式
  • 给resize事件增加防抖处理,避免拖拽调整窗口尺寸时回调高频触发导致性能问题
  • 给所有jQuery动画加stop()方法,解决快速滚动、快速调整窗口时动画排队、样式延迟生效的问题
修复后完整代码
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
    // 防抖工具函数
    function debounce(func, delay = 100) {
        let timer = null;
        return function(...args) {
            clearTimeout(timer);
            timer = setTimeout(() => func.apply(this, args), delay);
        }
    }

    // 大屏滚动头部交互
    function handleDesktopHeaderScroll() {
        const windowWidth = $(window).width();
        // 宽度不满足直接退出
        if (windowWidth < 1280) return;

        const scrollTop = $(window).scrollTop();
        if (scrollTop > 10) {
            $('#toggleNav').stop().show(300).css({ 'display': 'flex' });
            $('#articleGroupMenu').stop().hide(350);
            $('.sticky-wrapper,#headerContainer').css({
                "height": "162px",
                'transition': 'all 0.3s linear'
            });
        } else {
            $('#articleGroupMenu').stop().show(350);
            $('#toggleNav').stop().hide(300);
            $('.sticky-wrapper,#headerContainer').css({
                "height": "191px",
                'transition': 'all 0.3s linear'
            });
        }
    }

    // 小屏下重置头部为默认样式
    function resetMobileHeader() {
        const windowWidth = $(window).width();
        if (windowWidth >= 1280) return;
        
        $('#articleGroupMenu').show();
        $('#toggleNav').hide();
        $('.sticky-wrapper,#headerContainer').css({
            "height": "191px",
            'transition': 'none'
        });
    }

    // 统一绑定事件,避免重复绑定
    $(window).on('scroll', handleDesktopHeaderScroll);
    $(window).on('resize', debounce(function() {
        resetMobileHeader();
        handleDesktopHeaderScroll();
    }));

    // 初始化执行
    resetMobileHeader();
    handleDesktopHeaderScroll();
});
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 19:21:32