<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>倒计时</title>
</head>
<body>
<!-- 倒计时 -->
<div id="countdownContainer"></div>
</body>
<script>
/* 添加倒计时函数*/
(function () {
// 初始化倒计时功能
function initCountdown() {
initUI();
updateCountdowns();
setInterval(updateCountdowns, 1000);
}
// 创建初始用户界面
function initUI() {
var container = document.createElement('div');
container.id = 'countdownContainer';
document.body.appendChild(container);
var addButton = document.createElement("button");
addButton.innerHTML = "添加倒计时";
addButton.onclick = addCountdown;
document.body.appendChild(addButton);
}
// 更新倒计时显示
function updateCountdowns() {
var container = document.getElementById("countdownContainer");
container.innerHTML = "";
var countdowns = getCountdowns();
countdowns.forEach(function (countdown, index) {
var div = document.createElement("div");
div.innerHTML = `<strong>${countdown.title}</strong>: ${getTimeRemaining(countdown.date)} <button onclick="window.deleteCountdown(${index})">删除</button>`;
container.appendChild(div);
});
}
// 计算剩余时间
function getTimeRemaining(endDate) {
var total = Date.parse(endDate) - Date.parse(new Date());
var seconds = Math.floor((total / 1000) % 60);
var minutes = Math.floor((total / 1000 / 60) % 60);
var hours = Math.floor((total / (1000 * 60 * 60)) % 24);
var days = Math.floor(total / (1000 * 60 * 60 * 24));
return `${days}天 ${padZero(hours)}小时 ${padZero(minutes)}分钟 ${padZero(seconds)}秒`;
}
// 为数字小于10的前面添加0
function padZero(num) {
return num < 10 ? `0${num}` : num;
}
// 添加新的倒计时
function addCountdown() {
var formContainer = document.createElement("div");
formContainer.id = "countdownForm";
formContainer.innerHTML = `
<input type="text" id="countdownTitle" placeholder="提示信息">
<input type="datetime-local" id="countdownDate">
<button onclick="window.saveCountdown()">保存倒计时</button>
<button onclick="window.cancelCountdown()">取消</button>
`;
document.body.appendChild(formContainer);
formContainer.style.display = "block";
}
// 保存倒计时到LocalStorage
window.saveCountdown = function() {
var title = document.getElementById("countdownTitle").value;
var date = document.getElementById("countdownDate").value;
if (title && date) {
var countdowns = getCountdowns();
countdowns.push({ title: title, date: date });
localStorage.setItem("countdowns", JSON.stringify(countdowns));
document.getElementById("countdownForm").remove();
updateCountdowns();
}
}
// 删除指定的倒计时
window.deleteCountdown = function(index) {
var countdowns = getCountdowns();
countdowns.splice(index, 1);
localStorage.setItem("countdowns", JSON.stringify(countdowns));
updateCountdowns();
}
// 取消倒计时的添加
window.cancelCountdown = function() {
document.getElementById("countdownForm").remove();
}
// 从LocalStorage获取倒计时
function getCountdowns() {
return JSON.parse(localStorage.getItem("countdowns")) || [];
}
// 启动倒计时功能
window.onload = initCountdown;
})();
/* 添加倒计时函数 结束*/
</script>
</html>