You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何防止基于loopcounter.js的jQuery倒计时时钟随时间偏移?

解决loopcounter.js倒计时文本偏移问题

问题根源是倒计时的小时、分钟、秒数在位数变化时(比如从"10"变为"9"),元素宽度会随之改变,导致整个居中的文本出现偏移。以下是两种可行的解决方法:

方法1:为数字容器设置固定宽度

给每个数字容器设置固定宽度并让内部文本居中,确保数字位数变化时容器宽度不变,避免整体偏移:

body {
  background:#000000
}
.messaging {
  font-family:'Montserrat',sans-serif;
  text-align:center;
  color:#ffffff;
  font-weight:600;
  font-size:20px;
  line-height:25px;
}

.myCountdown {
  background:green;
  padding:10px;
  border-radius:10px;
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

/* 固定数字容器宽度,确保位数变化时宽度不变 */
.counter-hours, .counter-minutes, .counter-seconds {
  width: 30px;
  text-align: center;
}

方法2:使用等宽字体

等宽字体的每个字符宽度一致,数字位数变化时整体宽度不会明显波动,从根源上解决偏移问题:

/* 为数字容器设置等宽字体 */
.counter-hours, .counter-minutes, .counter-seconds {
  font-family: 'Courier New', monospace;
}

你可以单独使用其中一种方法,也可以两种结合,进一步提升稳定性。

修改后的完整代码示例:

<html>
  <head>
        <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
body {
  background:#000000
}
.messaging {
  font-family:'Montserrat',sans-serif;
  text-align:center;
  color:#ffffff;
  font-weight:600;
  font-size:20px;
  line-height:25px;
}

.myCountdown {
  background:green;
  padding:10px;
  border-radius:10px;
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.counter-hours, .counter-minutes, .counter-seconds {
  width: 30px;
  text-align: center;
  font-family: 'Courier New', monospace;
}
    </style>
  </head>
  <body>
    <p class="messaging">Album Drops in  <span class="countdown-wrap"><span class="myCountdown" data-date="2023-11-26 23:59:59">
                            <span class="counter-hours"></span> : <span class="counter-minutes"></span> : <span class="counter-seconds"></span>
                        </span></span></p>

    <script
  src="https://code.jquery.com/jquery-3.6.1.slim.min.js"
  integrity="sha256-w8CvhFs7iHNVUtnSP0YKEg00p9Ih13rlL9zGqvLdePA="
  crossorigin="anonymous"></script>
   <script src="https://www.jqueryscript.net/demo/countdown-date-loop-counter/js/loopcounter.js"></script>  
  </body>
 </html>

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 09:30:57