← 中文资源

简体中文版本

matchMedia 订阅断点变化

matchMedia 与样式表用同一 media 字符串判断断点:matches 是查询时刻的一次求值,变化靠 change 事件推送,回调里直接读事件值,不要轮询 innerWidth。

阅读英文原文

实现说明

底层就是函数 render。

使用要点

  • 用到了 document、window,需要在浏览器环境运行,Node 里直接跑会缺 API。
  • 直接运行文件,输出会带上标签,比如 layout:、reduced motion:——输出的每一行都能指回产生它的那次调用。

常见问题

「matchMedia 订阅断点变化」能在裸 Node.js 里跑吗?

不能——document、window 这些 API 由浏览器提供,Node 进程里拿不到。要执行的话,请在页面里(或 DevTools 控制台)运行。

签名一览:function render(layout: 'mobile' | 'desktop')

核心语句

query.addEventListener('change', (event) => {
  render(event.matches ? 'mobile' : 'desktop');
});

代码示例

// matchMedia turns a CSS breakpoint into subscribable state: the media string matches the stylesheet exactly,
// matches is a one-shot snapshot at query time, changes arrive via the change event
const query = window.matchMedia('(max-width: 768px)');

function render(layout: 'mobile' | 'desktop'): void {
  console.log('layout:', layout);
}

render(query.matches ? 'mobile' : 'desktop');

// MediaQueryListEvent carries matches: use the event value in the callback, never re-read the global
query.addEventListener('change', (event) => {
  render(event.matches ? 'mobile' : 'desktop');
});

// prefers-reduced-motion works the same way: respect the system's motion preference
const motionQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
console.log('reduced motion:', motionQuery.matches);

// The old addListener API is deprecated; never poll window.innerWidth for breakpoints
document.body.dataset.layout = query.matches ? 'mobile' : 'desktop';