jquery倒计时代码
jQuery倒计时代码实现
以下是几种常见的jQuery倒计时实现方式,适用于不同场景需求。
基础倒计时(固定时间)
$(document).ready(function() {
let count = 10; // 初始秒数
const countdown = setInterval(function() {
$("#countdown").text(count);
count--;
if (count < 0) {
clearInterval(countdown);
$("#countdown").text("时间到!");
}
}, 1000);
});
HTML部分需包含:

<div id="countdown">10</div>
指定目标时间的倒计时
计算到未来某个时间点的剩余时间:
function updateCountdown(endDate) {
const now = new Date();
const diff = endDate - now;
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const mins = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
const secs = Math.floor((diff % (1000 * 60)) / 1000);
$("#countdown").html(`${days}天 ${hours}时 ${mins}分 ${secs}秒`);
if (diff <= 0) {
clearInterval(timer);
$("#countdown").html("活动已结束");
}
}
const endDate = new Date("2023-12-31 23:59:59");
const timer = setInterval(() => updateCountdown(endDate), 1000);
带样式的倒计时
添加CSS美化显示效果:

#countdown {
font-size: 2em;
color: #ff5722;
text-align: center;
padding: 20px;
background: #f5f5f5;
border-radius: 5px;
}
用户交互式倒计时
允许用户输入倒计时时间:
$("#startBtn").click(function() {
const minutes = parseInt($("#minutesInput").val()) || 0;
let seconds = minutes * 60;
const timer = setInterval(function() {
const mins = Math.floor(seconds / 60);
const secs = seconds % 60;
$("#countdown").text(`${mins}:${secs < 10 ? '0' : ''}${secs}`);
seconds--;
if (seconds < 0) {
clearInterval(timer);
alert("时间到!");
}
}, 1000);
});
对应HTML:
<input type="number" id="minutesInput" placeholder="输入分钟数">
<button id="startBtn">开始倒计时</button>
<div id="countdown"></div>
注意事项
- 使用
clearInterval()防止内存泄漏 - 移动端建议使用CSS媒体查询优化显示
- 服务器时间同步问题可通过AJAX获取解决
- 时区处理建议使用UTC时间避免地域差异
以上代码可根据实际需求调整时间格式、显示样式或触发逻辑。






