var demo = document.getElementById("demo"); var timer = document.getElementById("timer"); var now = new Date(); var expire = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000); // 计算相差的时间(单位:毫秒) var diff = expire.getTime() - now.getTime(); function startTimer() { // 转换为天、小时、分钟、秒 var days = Math.floor(diff / (24 * 60 * 60 * 1000)); var hours = Math.floor((diff % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000)); var minutes = Math.floor((diff % (60 * 60 * 1000)) / (60 * 1000)); var seconds = Math.floor((diff % (60 * 1000)) / 1000); // 显示倒计时 demo.innerHTML = "距离过期还有:" + days + "天" + hours + "小时" + minutes + "分钟" + seconds + "秒"; diff -= 1000; // 如果还没到过期时间,继续倒计时 if (diff > 0) { setTimeout(startTimer, 1000); } else { // 到了过期时间,提示用户 timer.innerHTML = "已经过期!"; } } 封装这个函数
时间: 2024-02-14 12:24:09 浏览: 124
document.getElementsByName和document.getElementById 在IE与FF中不同实现
function countDown(expireDate, demoElement, timerElement) {
var demo = document.getElementById(demoElement);
var timer = document.getElementById(timerElement);
var now = new Date();
var expire = new Date(expireDate);
var diff = expire.getTime() - now.getTime();
function startTimer() {
var days = Math.floor(diff / (24 * 60 * 60 * 1000));
var hours = Math.floor((diff % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000));
var minutes = Math.floor((diff % (60 * 60 * 1000)) / (60 * 1000));
var seconds = Math.floor((diff % (60 * 1000)) / 1000);
demo.innerHTML = "距离过期还有:" + days + "天" + hours + "小时" + minutes + "分钟" + seconds + "秒";
diff -= 1000;
if (diff > 0) {
setTimeout(startTimer, 1000);
} else {
timer.innerHTML = "已经过期!";
}
}
startTimer();
}
// 使用方式:
countDown("2022-12-31", "demo", "timer");
// 参数说明:第一个参数是过期日期,第二个参数是显示倒计时的元素的 ID,第三个参数是显示过期提示的元素的 ID。
阅读全文