如何用jQuery将.countdown-timer类的时间文本转为多实例独立倒计时器
多实例倒计时器实现方案
完整可运行代码
HTML 代码
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <!-- 可添加任意多个带 countdown-timer 类的元素,每个独立倒计时 --> <span class="countdown-timer">Nov-07-2021 08:34:00 EST</span> <span class="countdown-timer">Dec-25-2024 00:00:00 EST</span>
JS 代码
$(function() { // 遍历所有倒计时元素,独立处理每个实例 $('.countdown-timer').each(function() { const $currentEl = $(this); // 读取元素内原始时间字符串,转换为毫秒级时间戳存储 const targetTimestamp = new Date($.trim($currentEl.text())).getTime(); // 为当前元素单独创建计时器,避免多个实例互相干扰 const countInterval = setInterval(() => { const nowTimestamp = Date.now(); const timeDiff = targetTimestamp - nowTimestamp; // 倒计时结束逻辑 if (timeDiff <= 0) { clearInterval(countInterval); $currentEl.text('ENDED'); return; } // 计算剩余天/时/分/秒 const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24)); const hours = Math.floor((timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); const minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60)); const seconds = Math.floor((timeDiff % (1000 * 60)) / 1000); // 格式化输出,不足两位补前导0 let showText = ''; if (days > 0) showText += `${days}天 `; showText += `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`; $currentEl.text(showText); }, 1000); }); });
核心优化说明
- 支持同一页面任意多个倒计时实例,每个实例独立运行互不影响
- 基于时间戳差值计算倒计时,精度高于直接读取DOM文本修改的方案,不存在累计误差
- 自动适配任意时长的倒计时,支持展示天/时/分/秒,不止分钟级
- 倒计时结束后自动销毁对应计时器,固定显示
ENDED,不会出现重新计时的问题
内容的提问来源于stack exchange,提问作者Adyyda
相关产品推荐
相关产品推荐

