让同步提示旁的小圆点跟随系统设置,用 matchMedia 接管偏好变化和缩放动画的启停。
让已经打开的页面跟上「减少动态效果」设置
作者:像素漫游
时间:2026-12-05
浏览:306
同步面板还开着,「正在同步」旁边的小圆点一大一小。去系统设置打开「减少动态效果」,再切回页面。如果圆点还在动,刷新以后才停,我会先翻一下启动动画的代码,看看是不是写了 const reduceMotion = matchMedia(query).matches。
reduceMotion 记下的是读取那一刻的布尔值。系统偏好变了,已经创建的动画照样播。把 matchMedia() 返回的 MediaQueryList 留下来,打开面板时调一次 sync(query)。后面匹配结果变了,change 事件也带着 matches,直接交给同一个函数。
页面里放一个 <span id="badge" aria-hidden="true" style="display:inline-block">●</span> 正在同步,等圆点插入页面后再执行脚本。圆点只负责动效,同步状态由旁边的文字说明。
function mountPulse(badge) {
const query = matchMedia("(prefers-reduced-motion: reduce)");
let animation;
function sync({ matches }) {
if (matches) {
animation?.cancel();
animation = undefined;
} else if (!animation) {
animation = badge.animate(
[{ transform: "scale(1)" }, { transform: "scale(1.12)" }],
{ duration: 550, iterations: Infinity, direction: "alternate" },
);
}
console.log(`reduce=${matches} pulse=${animation ? "on" : "off"}`);
}
query.addEventListener("change", sync);
sync(query);
return () => {
query.removeEventListener("change", sync);
animation?.cancel();
};
}
const stopPulse = mountPulse(document.querySelector("#badge"));

关着「减少动态效果」打开面板,再打开这项设置,最后关回去。圆点应该先缩放,再停住,然后从头开始缩放。「正在同步」一直可见。第一条日志来自 sync(query),后两条对应两次偏好变化。

cancel() 会撤掉这段动画产生的缩放效果,圆点回到基础样式。顺手把 animation 清掉。单调用 cancel(),变量还指着原来的实例,下一次跑到 else if (!animation) 就进不去了。

关面板时,把 stopPulse() 接在移除圆点的地方。如果只取消动画,旧监听下次还会响应系统设置,甚至给已经移出页面的圆点重新创建动画。面板反复开关时,这类遗留回调才容易露出来。
实用工具推荐
电子包浆
使用 ›绿化、压缩、噪点和虚拟水印,自由调节做旧程度。
图片压缩
使用 ›选择画质和输出格式,预览压缩前后的大小。
作者最新文章
相关文章