CSS 媒体功能 prefers-reduced-motion 允许检查用户是否在其设备上启用了设置以减少不必要的动画。此设置通知设备的浏览器,用户已选择一个界面,该界面会删除、最小化或替换运动驱动的动画。
可能的值
- no-preference − 此值表示用户未在其设备上指示任何特定偏好。关键字值被视为 false。
- reduce − 此值表示用户已在其设备上激活了 reduce motion 设置。关键字值被视为 true。
语法
prefers-reduced-motion: no-preference|reduce;
CSS prefers-reduced-motion - 示例
如果打开了“减弱动态效果”设置,则此页面上的绿色框将移动得更慢、更顺畅,背景将变为粉红色,文本下方将有一行。如果您没有打开“减弱动态效果”设置,则绿色框将正常移动,背景将保持绿色。
- 脉冲 − 此动画使元素每四秒脉冲一次。
- 溶解 - 此动画使元素每两秒淡入和淡出一次。
按照链接上的步骤模拟 prefers-reduced-motion 模式并测试以下示例。
这是一个例子 -
<html>
<head>
<style>
.box {
animation: pulse 4s linear;
background-color: green;
color: white;
width: 160px;
padding: 10px;
border-radius: 5px;
}
@media (prefers-reduced-motion) {
.box {
animation: dissolve 2s linear;
background-color: pink;
text-decoration: overline;
}
}
@keyframes pulse {
0% {
transform: scale(0.5);
}
50% {
transform: scale(0.8);
}
100% {
transform: scale(08.);
}
}
@keyframes dissolve {
0% {
opacity: 0.7;
}
50% {
opacity: 0.5;
}
100% {
opacity: 0.7;
}
}
</style>
</head>
<body>
<div class="box">
prefers-reduced-motion
</div>
</body>
</html>
CSS prefers-reduced-motion - 无偏好值
带有 (prefers-reduced-motion: no-prefernce) 的@media查询将为喜欢减少运动的用户禁用动画 (盒子将保持静止)。
这是一个例子 -
<html>
<head>
<style>
.box {
width: 220px;
height: 100px;
background-color: violet;
animation: moveRight 2s linear infinite;
}
@keyframes moveRight {
0% {
transform: translateX(0);
}
100% {
transform: translateX(100%);
}
}
@media (prefers-reduced-motion: no-preference) {
.box {
animation: none;
transform: none;
}
}
</style>
</head>
<body>
<div class="container">
<div class="box">prefers-reduced-motion: no-preference</div>
</div>
</body>
</html>
CSS prefers-reduced-motion - reduce 值
使用 (prefers-reduced-motion: reduce) 的@media查询检查用户对减少运动的偏好。如果用户在其设备上启用了减少运动设置,则盒子将在连续循环中从左到右水平移动。
这是一个例子 -
<html>
<head>
<style>
.box {
width: 220px;
height: 100px;
background-color: violet;
animation: moveRight 2s linear infinite;
}
@keyframes moveRight {
0% {
transform: translateX(0);
}
100% {
transform: translateX(100%);
}
}
@media (prefers-reduced-motion: reduce) {
.box {
animation: none;
}
}
</style>
</head>
<body>
<div class="container">
<div class="box">prefers-reduced-motion: reduce</div>
</div>
</body>
</html>
下表显示了如何在不同操作系统的 Firefox 中启用减少运动功能:
操作系统 | 如何在Firefox中启用减少运动 |
---|---|
GTK/GNOME | 设置>辅助功能>查看>减少动画 |
Older versions of GNOME | GNOME 调整 > 常规选项卡(或外观,取决于版本) > 动画 |
Plasma/KDE | 系统设置 > 工作区行为 -> 常规行为 > “动画速度”设置为“即时” |
Windows 10 | 在 Windows 中>显示动画>易用性设置> |
Windows 11 | 动画效果>视觉效果>辅助功能设置> |
macOS | “系统偏好设置”>“辅助功能”>“显示”>“减弱动态效果” |
iOS | Motion >辅助功能>设置 |
Android 9+ | >辅助功能>删除动画的设置 |
Firefox about:config | 添加一个名为 ui.prefersReducedMotion 的数字首选项,并将其值设置为 0 表示完整动画,或将其值设置为 1 以指示减少运动的首选项。. |