You need to enable JavaScript to run this app. JavaScript如何仅当window.innerWidth大于599时调用onscroll滚动函数
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript如何仅当window.innerWidth大于599时调用onscroll滚动函数

问题原因分析
  • 语法错误:resize事件监听器缺少闭合的右括号,导致代码初始化直接报错,后续逻辑全部无法执行。原代码里window.addEventListener('resize', function(){...}末尾只有};,缺少了)来闭合addEventListener的参数。
  • 绑定时机缺失:仅在窗口触发resize事件时才会绑定滚动事件,如果页面加载完成后窗口宽度本身就大于599px,且用户没有触发过窗口缩放,滚动事件永远不会被绑定。
  • 变量提升问题:const声明的scroller函数不存在变量提升,原代码把scroller的定义写在了事件监听器注册逻辑的后面,如果事件触发时scroller还未完成初始化,会抛出未定义的错误。
  • 缺少解绑逻辑:当窗口宽度从大于599px缩到小于等于599px时,没有解绑滚动事件,scroller还是会继续执行。
修正后的代码
// 先定义滚动处理函数,避免变量提升问题
const scroller = () => {
  // 进度滚动条逻辑
  var winScroll = document.body.scrollTop || document.documentElement.scrollTop;
  var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
  var scrolled = (winScroll / height) * 100;
  document.getElementById("scrollBar").style.width = scrolled + "%";

  // 滚动时折叠头部逻辑
  if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
    document.querySelector("header").style.height = "5rem";
    document.querySelector("h1").style.display = "none";
    document.querySelector("nav ul").style.top = "1rem";
    document.getElementById("wrapper").style.marginTop = "10rem";
    document.getElementById("scrollContainer").style.top = "5rem";
    document.getElementById("scrollBar").style.top = "5rem";
  } else {
    document.querySelector("header").style.height = "15rem";
    document.querySelector("h1").style.display = "inherit";
    document.querySelector("nav ul").style.top = "3rem";
    document.getElementById("wrapper").style.marginTop = "15rem";
    document.getElementById("scrollContainer").style.top = "inherit";
    document.getElementById("scrollBar").style.top = "inherit";
  } 
};

// 滚动事件绑定/解绑处理函数
function toggleScrollListener() {
  if (window.innerWidth > 599) {
    window.addEventListener('scroll', scroller);
    // 首次绑定时主动执行一次,适配页面初始滚动位置
    scroller();
  } else {
    window.removeEventListener('scroll', scroller);
  }
}

// 页面加载完成后先执行一次判断
window.addEventListener('load', toggleScrollListener);
// 窗口大小变化时重新判断
window.addEventListener('resize', toggleScrollListener);
补充优化建议
  • 可以给resize事件加防抖,避免窗口缩放过程中频繁触发判断逻辑,减少性能损耗
  • 操作DOM前最好先判断对应元素是否存在,避免页面缺少对应元素时抛出空指针错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 18:57:03