prefers-reduced-motion媒体查询可检测用户是否已请求操作系统最小化其使用的animation或motion。

语法

  • no-preference:用户未修改系统animation相关特性。
  • reduce:如果用户修改了系统设置,将animation效果最小化,最好所有的不必要的motion都能被移除。

示例

reduce

<div class="animation">animated box</div>
.animation {
  animation: vibrate 0.3s linear infinite both; 
}
@media (prefers-reduced-motion: reduce) {
  .animation {
    animation: none;
  }
}
@keyframes vibrate {
  0% {
    transform: translate(0);
  }
  50% {
    transform: translate(-2px, 2px);
  }
  100% {
    transform: translate(0);
  }
}

no-preference

@media (prefers-reduced-motion: no-preference) {
  .App-logo {
    animation: App-logo-spin infinite 20s linear;
  }
}
@keyframes App-logo-spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

您可以将所有与animation相关的CSS放到单独的样式表中,通过link元素上的media属性有条件地加载:

<link rel="stylesheet" href="animations.css" media="(prefers-reduced-motion: no-preference)">

在操作系统中关闭motion

在macOS中关闭motion

在macOS中关闭motion

在android中关闭motion

在android中关闭motion

在JavaScript中监听prefers-reduced-motion

对于JavaScript animation,我必须亲自监听更改,然后手动停止可能正在运行的animation(如果用户允许,请重新启动它们):

const mediaQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
mediaQuery.addEventListener('change', () => {
  console.log(mediaQuery.media, mediaQuery.matches);
  // Stop JavaScript-based animations.
});

不要这样写window.matchMedia('prefers-reduced-motion: reduce')

强制减少所有网站上的motion

不是所有的网站都会使用prefers-reduced-motion,实现此目的的一种方法是将包含以下CSS的样式表插入您访问的每个网页中。有几个浏览器扩展允许这样做。

@media (prefers-reduced-motion: reduce) {
  *, ::before, ::after {
    animation-delay: -1ms !important;
    animation-duration: 1ms !important;    
    animation-iteration-count: 1 !important;
    background-attachment: initial !important;
    scroll-behavior: auto !important;
    transition-duration: 0s !important;
    transition-delay: 0s !important;
  }
}

prefers-reduced-motion: Sometimes less movement is more