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

如何让matchMedia监听器在页面加载或刷新时自动触发?

解决页面加载/刷新时自动执行媒体查询逻辑的问题

原代码仅在视口尺寸变化时触发监听器,但页面首次加载或刷新时,不会主动检查当前视口对应的设备类型。要解决这个问题,只需补充初始化时的检查逻辑,同时把重复的提示逻辑抽成独立函数复用,避免代码冗余。

修改后的代码如下:

function screenSize(){
  const mobile = window.matchMedia('screen and (max-width: 573px)');
  const tablet = window.matchMedia('screen and (min-width: 572px) and (max-width: 990px)');
  const desktop = window.matchMedia('screen and (min-width: 990px)');

  // 抽离独立的提示函数
  function showMobileAlert() {
    alert("Mobile-view");
  }
  function showTabletAlert() {
    alert("Tablet-view");
  }
  function showDesktopAlert() {
    alert("desktop-view");
  }

  // 页面加载时主动检查并执行
  if (mobile.matches) showMobileAlert();
  if (tablet.matches) showTabletAlert();
  if (desktop.matches) showDesktopAlert();

  // 尺寸变化时的监听器
  mobile.addListener(function(evt){
    if(evt.matches) {
      showMobileAlert();
    }
  });

  tablet.addListener(function(evt){
    if(evt.matches) {
      showTabletAlert();
    }
  });

  desktop.addListener(function(evt){
    if(evt.matches) {
      showDesktopAlert();
    }
  });
}

screenSize();

关键修改点:

  • 将每个设备类型的提示逻辑封装成独立函数,既保证代码复用,也让结构更清晰
  • 在初始化媒体查询对象后,立即通过matches属性检查当前视口是否匹配对应的设备类型,匹配则直接调用提示函数,实现页面加载/刷新时的自动触发
  • 原有尺寸变化的监听器逻辑保持不变,依然调用这些独立函数,确保尺寸调整时的功能正常

内容的提问来源于stack exchange,提问作者Kiki-ko

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 03:07:49