如何用CSS将倒计时计数器值以分钟为单位显示?
纯CSS实现倒计时显示剩余分钟数方案
你完全可以不用JavaScript实现,核心问题是之前你试图直接在content里输出计算结果,但CSS的content不支持直接解析calc表达式,必须结合自定义属性和计数器来处理。
修改后的代码实现
@property --t { syntax: "<number>"; initial-value: 1500; inherits: true; } /* 定义分钟变量,类型约束为整数,自动处理取整 */ @property --m { syntax: "<integer>"; initial-value: 25; inherits: true; } /* 核心动画:让秒数从1500递减到0 */ @keyframes countdown-tick { to { --t: 0 } } .countdown { /* 通过总秒数计算剩余分钟,integer类型会自动向下取整 */ --m: calc(var(--t) / 60); display: grid; margin: 1em auto; width: 20em; height: 20em; animation: countdown-tick 1500s linear forwards; } .countdown::after { grid-column: 1; grid-row: 1; place-self: center; font: 5em/2 ubuntu mono, consolas, monaco, monospace; /* 用分钟变量初始化计数器 */ counter-reset: remaining-minutes var(--m); /* 输出计数器值,可自定义显示文本 */ content: counter(remaining-minutes) " 分钟"; } /* 保留环形进度动画(可选) */ .countdown svg { grid-column: 1; grid-row: 1; width: 100%; height: 100%; transform: rotate(-90deg); } .countdown circle { fill: none; stroke: #ddd; } .countdown circle:last-of-type { stroke: #222; stroke-dasharray: 1; stroke-dashoffset: calc(1 - var(--t)/1500); }
<body> <div style="font: 5em/2 ubuntu mono, consolas, monaco, monospace;color:black;text-align: center;">Processing</div> <div class="countdown"> <svg viewBox="-50 -50 100 100" stroke-width="10"> <circle r="45"></circle> <circle r="45" pathLength="1"></circle> </svg> </div> </body>
关键逻辑说明
- 自定义属性类型约束:通过
@property将--m定义为<integer>类型,这样当用calc(var(--t)/60)赋值时,CSS会自动将小数结果向下取整,正好符合剩余分钟的计算逻辑(比如1499秒对应24分钟)。 - 计数器桥接:
content无法直接输出自定义属性的计算结果,但可以通过counter-reset将整数变量绑定到计数器,再用counter()输出到content中。 - 同步环形进度:原有的环形动画可以保留,通过
stroke-dashoffset结合--t变量,实现进度条与分钟倒计时同步变化。
如果需要显示分:秒格式,纯CSS也能实现(需要额外定义秒数变量--s: calc(var(--t) % 60)),但补零逻辑会比较繁琐;如果只是显示剩余分钟数,以上方案完全满足需求,无需引入JavaScript。
内容的提问来源于stack exchange,提问作者Mike
相关产品推荐
相关产品推荐

