<!DOCTYPE html>
<html>
<head>
<title>表格中的时间倒计时</title>
</head>
<body>
<table>
<tr>
<td id="start1">2023-09-15 10:00:00</td>
<td id="end1">2023-09-15 12:00:00</td>
<td id="countdown1"></td>
</tr>
<tr>
<td id="start2">2023-09-16 14:00:00</td>
<td id="end2">2023-09-16 16:30:00</td>
<td id="countdown2"></td>
</tr>
<tr>
<td id="start3">2023-09-17 09:30:00</td>
<td id="end3">2023-09-17 10:30:00</td>
<td id="countdown3"></td>
</tr>
</table>
<script>
// 等待整个文档加载完成后再执行 JavaScript 代码
window.onload = function () {
// 更新指定<tr>中的倒计时
function updateCountdown(tr, index) {
// 获取开始时间和结束时间的<td>元素
var startTd = tr.querySelector("#start" + (index + 1));
var endTd = tr.querySelector("#end" + (index + 1));
if (startTd && endTd) {
var startDateStr = startTd.textContent;
var endDateStr = endTd.textContent;
var startTime = new Date(startDateStr);
var endTime = new Date(endDateStr);
var currentTime = new Date();
var timeDifference = endTime - currentTime;
// 获取倒计时的<td>元素
var countdownElement = tr.querySelector("#countdown" + (index + 1));
if (countdownElement) {
countdownElement.textContent = formatTime(timeDifference);
if (timeDifference <= 0) {
clearInterval(countdownInterval[index]); // 倒计时结束时清除定时器
}
}
}
}
// 格式化剩余时间
function formatTime(milliseconds) {
var seconds = Math.floor(milliseconds / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
seconds = seconds % 60;
minutes = minutes % 60;
hours = hours % 24;
return days + " 天 " + hours + " 小时 " + minutes + " 分钟 " + seconds + " 秒";
}
// 获取所有<tr>元素
var trElements = document.querySelectorAll("tr");
var trArray = Array.from(trElements);
// 启动每个倒计时的定时器
var countdownInterval = [];
trArray.forEach(function (tr, index) {
countdownInterval[index] = setInterval(function () {
updateCountdown(tr, index);
}, 1000);
});
};
</script>
</body>
</html>
使用 window.onload 事件等待整个文档加载完成后再进行操作。