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

如何用jQuery判断窗口宽度是否小于em/rem等非像素单位?

嘿,这个场景我太熟悉了!你想把Sass里的断点和JS的视口判断结合起来,核心其实是解决单位转换的问题——因为JS拿到的视口宽度是像素值,而你的断点用的是em,得先把em转成px才能比较。我给你一步步拆解:

第一步:把Sass断点同步到JS(避免重复维护)

硬写数值到JS里太容易出错了,最好让JS直接读取Sass里的断点配置。如果用Webpack/Vite这类构建工具,你可以在Sass文件里用:export导出变量:

$width_breakpoints: (
  small: 39.9375em,
  medium: 40em,
  large: 76em
);

// 导出给JS用
:export {
  smallBreakpoint: #{map-get($width_breakpoints, small)};
  mediumBreakpoint: #{map-get($width_breakpoints, medium)};
  largeBreakpoint: #{map-get($width_breakpoints, large)};
}

然后在JS里导入这个变量:

import breakpoints from './path/to/your/breakpoints.scss';
第二步:写单位转换函数

不同单位的转换逻辑不一样,我给你针对em/rem/百分比分别写了函数:

转换em到px

重点:媒体查询里的em是**基于浏览器默认字体大小(通常16px)**的,哪怕你改了根元素的font-size,媒体查询的em还是按16px算(这是W3C的规定),所以直接乘16就行:

function emToPx(emStr) {
  // 把类似"39.9375em"的字符串转成数字
  const emValue = parseFloat(emStr);
  return emValue * 16;
}

转换rem到px

rem是相对于根元素的font-size,所以要先获取根元素实际计算后的字体大小:

function remToPx(remStr) {
  const remValue = parseFloat(remStr);
  const rootFontSize = parseFloat(getComputedStyle(document.documentElement).fontSize);
  return remValue * rootFontSize;
}

转换百分比到px(视口相对)

如果你的断点是相对于视口宽度的百分比(比如50%),就用这个函数:

function percentageToViewportPx(percentStr) {
  const percentValue = parseFloat(percentStr);
  return (window.innerWidth * percentValue) / 100;
}
第三步:实现视口判断和类名切换

现在就可以写核心逻辑了,记得加上resize监听,最好加个防抖避免频繁触发:

// 防抖函数,优化resize性能
function debounce(func, delay = 150) {
  let timeoutId;
  return (...args) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func.apply(this, args), delay);
  };
}

function updateMobileClass() {
  // 把Sass里的small断点转成px
  const smallBreakpointPx = emToPx(breakpoints.smallBreakpoint);
  const isMobile = window.innerWidth < smallBreakpointPx;
  
  // 替换成你要操作的元素选择器
  const targetElement = document.querySelector('.your-target-element');
  
  if (isMobile) {
    targetElement.classList.add('current-mode-mobile');
  } else {
    targetElement.classList.remove('current-mode-mobile');
  }
}

// 页面加载时执行一次
updateMobileClass();
// 监听窗口 resize,用防抖优化
window.addEventListener('resize', debounce(updateMobileClass));
注意事项
  • 如果你不用构建工具,没法用:export的话,那只能手动把Sass断点的数值转成px写进JS里(比如39.9375em = 39.9375*16 = 639px),记得以后改Sass断点时同步更新JS。
  • 要是你的百分比断点是相对于某个父元素的(不是视口),那要把函数里的window.innerWidth换成父元素的offsetWidth。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:21:14