prefers-reduced-motion Downgrades Animation
matchMedia reads the prefers-reduced-motion preference, so decorative animation durations collapse to zero for users who asked for less motion.
Code
// matchMedia 读取系统级用户偏好:减弱动效的请求要被兑现
const reduced = matchMedia('(prefers-reduced-motion: reduce)');
// 降级:偏好命中时装饰性动画时长归零,功能不受影响
function durationFor(baseMs) {
return reduced.matches ? 0 : baseMs;
}
console.log('prefers reduced motion:', reduced.matches);
console.log('panel duration:', durationFor(240), 'ms');
// 系统设置切换时 change 事件即时到达,运行中的页面同步降级或恢复
const onChange = (event) => console.log('preference changed:', event.matches);
reduced.addEventListener('change', onChange);
reduced.removeEventListener('change', onChange);How the snippet works
Read it this way: everything runs through the functions onChange and durationFor, doing all the work.
Applying it
The main signature reads const onChange = (event)
The demo output is labeled (prefers reduced motion:, panel duration:, preference changed:), so every line in the printed output names the step that produced it.
Statements that matter
reduced.addEventListener('change', onChange);
return reduced.matches ? 0 : baseMs;
Interactive Tools for This Topic
WCAG Color Contrast CheckerCalculate WCAG 2.1 color contrast ratios between foreground and background colors. Verify AA and AAA compliance levels for normal and large text accessibility.Tailwind Color Palette GeneratorGenerate a balanced 50-950 Tailwind CSS custom property color scale from any hex, RGB, or HSL base color with WCAG 2.1 contrast ratios for every stop.Cubic Bezier PreviewPreview a CSS cubic-bezier() easing curve, validate the control points, and sample the progress mapping from input to output value.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.
FAQ
- Will the snippet run without installing packages?
- Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `onChange`, `durationFor` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.