<iframe allowfullscreen="true" data-mediaembed="bilibili" frameborder="0" id="YBkSphtY-1729578946329" src="https://player.bilibili.com/player.html?aid=113349605985664"></iframe>
html倒计时
<!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>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
@keyframes backgroundChange {
0% { background-image: url('file:///D:/img/706.png'); }
20% { background-image: url('file:///D:/img/771.png'); }
40% { background-image: url('file:///D:/img/772.png'); }
60% { background-image: url('file:///D:/img/773.png'); }
80% { background-image: url('file:///D:/img/774.png'); }
100% { background-image: url('file:///D:/img/706.png'); }
}
body {
width: 100vw;
height: 100vh;
animation: backgroundChange 10s infinite; /* 设置动画,时间可以根据需要调整 */
/* 替换为你的图片路径 */
background-size: cover;
/* 使背景图像覆盖整个元素 */
background-position: center;
/* 使背景图像居中 */
background-repeat: no-repeat;
/* 不重复背景图像 */
overflow: hidden;
/* 溢出 隐藏*/
font-size: 1.5rem;
text-shadow: 1px 1px 1px #000000;
}
h3,
h1 {
text-align: center;
color: #ffffff;
text-shadow: 1px 1px 1px #000;
}
.countdownContainer {
width: 100%;
display: flex;
/* flex-direction: column; */
align-items: center;
margin: 1px;
padding: 1px;
border: #e6a23c solid 2px;
font-size: 1.5rem;
}
/* 默认倒计时 */
#defaultCountdownContainer {
/* width: 100%; */
display: flex;
flex-direction: column;
border: #e6a23c solid 2px;
margin: 2px 10px;
padding: 2px 10px;
}
div[id^="countdown-"] {
background: rgba(29, 29, 29, 0.708);
border-radius: 2px;
backdrop-filter: blur(1px);
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.982);
text-shadow: 1px 1px 1px #000000;
font-weight: 500;
border: 2px solid #fff;
}
div[id^="countdown-"]::after {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
border-radius: 2px;
/* background: #141111; */
/* 底部分割线 */
background-image: url('file:///D:/img/42.png');
/* 替换为你的图片路径 */
background-size: cover;
/* 使背景图像覆盖整个元素 */
background-position: center;
/* 使背景图像居中 */
background-repeat: no-repeat;
/* 不重复背景图像 */
}
/* 添加的倒计时 */
#uniqueCountdowns {
/* width: 100%; */
display: flex;
flex-direction: column;
align-items: center;
margin: 1px;
padding: 1px;
border: #ffffff solid 2px;
}
.actionButtons {
width: 100%;
display: flex;
flex-direction: row;
}
.actionButtons button {
width: 100%;
}
.uniqueDeleteButton {
/* 删除按钮 */
color: red;
}
.operativeFunction {
/* height: 100%; */
color: #fffcfc;
text-shadow: 1px 1px 1px #000;
background: #0bb81186;
/* 文本竖排 */
writing-mode: vertical-rl;
/* 文字间距 */
letter-spacing: 20px;
font-size: 25px;
padding-right: 10px;
background-image: linear-gradient(to top left,
rgba(0, 0, 0, 0.2),
rgba(0, 0, 0, 0.2) 30%,
rgba(0, 0, 0, 0));
box-shadow:
inset 2px 2px 3px rgba(255, 255, 255, 0.6),
inset -2px -2px 3px rgba(0, 0, 0, 0.6);
backdrop-filter: blur(2px);
}
.countdown-Buttons {
display: flex;
border: #e6a23c solid 2px;
color: #f56c6c;
}
.countdown-container form {
width: 100%;
display: flex;
}
.full-width {
width: 100%;
}
.countdown-container,
#uniqueCountdowns p {
width: 100%;
}
#uniqueCountdowns b {
color: hsla(160, 100%, 37%, 0.63);
text-shadow: 1px 1px 1px #000000;
border-radius: 4px;
margin: 4px 6px;
padding: 2px;
font-size: 1.5rem;
background: #14111177;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.669);
}
#uniqueCountdowns p label {
width: 100%;
margin: 2px;
border-radius: 2px;
backdrop-filter: blur(1px);
display: flex;
justify-content: space-between;
}
#uniqueCountdowns p label::after {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
border-radius: 2px;
background: #141111b7;
}
.countdown-container,
.uniqueCountdownCheckbox,
.uniqueEditButton,
.uniqueDeleteButton,
.finishButton {
/* 隐藏 */
display: none;
}
.uniqueCountdownCheckbox {
/* 复选框 */
transform: scale(1.8);
margin: 0 8px;
}
#uniqueCountdowns p.FinishTask {
position: relative;
/* 使子元素基于这个元素定位 */
text-decoration: line-through;
text-decoration-color: rgba(255, 253, 253, 0);
text-decoration-thickness: 2px;
color: transparent;
/* 将文本颜色设置为透明 */
}
</style>
<body>
<h1>倒计时功能实现</h1>
<div class="countdownContainer">
<div id="defaultCountdownContainer">
<h3>内置倒计时</h3>
</div> <!-- 默认倒计时容器 -->
<div class="countdown-Buttons">
<button id="operativeFunction" class="operativeFunction">操作</button>
<div id="uniqueCountdowns"> <!-- 用户添加的倒计时容器 -->
<h3>添加倒计时</h3>
<div class="actionButtons">
<button class="uniqueEditButton" onclick="editSelectedCountdown()">修改</button>
<button class="uniqueDeleteButton" onclick="deleteSelectedCountdown()">删除</button>
</div>
<div class="countdown-container">
<form>
<input type="text" id="uniquePromptInput" class="full-width" placeholder="提示信息">
<input type="datetime-local" id="uniqueDatetimeInput" class="full-width">
<button id="uniqueSaveButton" class="full-width" onclick="saveCountdown()">保存</button>
</form>
</div>
</div>
</div>
</div>
</body>
<script>
/* 倒计时功能实现开始*/
const defaultCountdowns = [
{ prompt: "元旦", datetime: "202501010000" },
{ prompt: "春节", datetime: "202502120000" },
{ prompt: "清明节", datetime: "202504040000" },
{ prompt: "劳动节", datetime: "202505010000" },
{ prompt: "端午节", datetime: "202506020000" },
{ prompt: "中秋节", datetime: "202509210000" },
{ prompt: "国庆节", datetime: "202510010000" },
];
const elementColors = ["#FF9933", "#3399FF", "#66c6ac", "#CC66FF", "#66CC66", "#99CCFF", "#FFCC33"];
let colorIndex = 0;
// 颜色函数:返回一个随机颜色,从预定义的颜色数组中选择。
function getRandomColor() {
colorIndex = (colorIndex + 1) % elementColors.length;
return elementColors[colorIndex];
}
// 零填充函数:返回一个字符串,如果数字小于10,则在左侧补零。
const padZero = num => num < 10 ? `0${num}` : num;
// 格式化日期函数:返回一个字符串,格式为"年-月-日 时:分"。
function formatDate(targetDate) {
const hours = targetDate.getHours();
const minutes = targetDate.getMinutes();
let timeString = '';
if (hours !== 0 || minutes !== 0) {
timeString = targetDate.toLocaleTimeString('zh-CN', {
hour: '2-digit',
minute: '2-digit',
});
}
return targetDate.getFullYear() + '年' +
(targetDate.getMonth() + 1).toString().padStart(2, '0') + '月' +
targetDate.getDate().toString().padStart(2, '0') + '日 ' + timeString;
}
// 更新倒计时函数...
// 启动默认倒计时函数...
// 格式化日期为"年-月-日 时:分"的函数
function formatDatetime(datetimeInput) {
// 确保传入字符串长度为12
if (datetimeInput.length !== 12) {
console.error("输入格式错误,应该为12位字符串:", datetimeInput);
return "无效日期";
}
const year = datetimeInput.slice(0, 4);
const month = datetimeInput.slice(4, 6);
const day = datetimeInput.slice(6, 8);
const hours = datetimeInput.slice(8, 10);
const minutes = datetimeInput.slice(10, 12);
const formattedInput = `${year}-${month}-${day}T${hours}:${minutes}`;
console.log("Formatted Input:", formattedInput);
const date = new Date(formattedInput);
if (isNaN(date.getTime())) {
console.error("无效的日期:", datetimeInput);
return "无效日期";
}
const formattedYear = date.getFullYear();
const formattedMonth = padZero(date.getMonth() + 1);
const formattedDay = padZero(date.getDate());
const formattedHours = padZero(date.getHours());
const formattedMinutes = padZero(date.getMinutes());
if (formattedHours === "00" && formattedMinutes === "00") {
return `${formattedYear}年${formattedMonth}月${formattedDay}日`;
}
return `${formattedYear}年${formattedMonth}月${formattedDay}日 ${formattedHours}:${formattedMinutes}`;
}
// 更新倒计时函数:更新倒计时显示,包括剩余时间和结束日期的格式化,并设置样式和颜色
function updateCountdown(elementId, targetDate, promptText, isDefault = false) {
const countdownElement = document.getElementById(elementId);
if (isDefault) {
countdownElement.textContent = promptText;
countdownElement.style.color = getRandomColor();
}
const endDateStr = formatDate(targetDate);
const update = () => {
const now = new Date();
const total = targetDate - now;
const absTotal = Math.abs(total);
const seconds = Math.floor((absTotal / 1000) % 60);
const minutes = Math.floor((absTotal / 1000 / 60) % 60);
const hours = Math.floor((absTotal / (1000 * 60 * 60)) % 24);
const days = Math.floor(absTotal / (1000 * 60 * 60 * 24));
const timeStr = `${days}天${padZero(hours)}:${padZero(minutes)}:${padZero(seconds)}`;
countdownElement.textContent = `${endDateStr}(${promptText}): ${total <= 0 ? `-${timeStr}` : timeStr} `;
if (!isDefault) {
countdownElement.style.color = getRandomColor();
}
};
update();
setInterval(update, 1000);
}
// 启动默认倒计时函数
defaultCountdowns.forEach(countdown => {
const countdownId = `countdown-${countdown.prompt}`;
const countdownDiv = document.createElement('div');
countdownDiv.id = countdownId;
document.getElementById('defaultCountdownContainer').appendChild(countdownDiv);
updateCountdown(countdownId, new Date(countdown.datetime.slice(0, 4), countdown.datetime.slice(4, 6) - 1, countdown.datetime.slice(6, 8), countdown.datetime.slice(8, 10), countdown.datetime.slice(10, 12)), countdown.prompt, true);
});
// 创建倒计时元素函数:根据输入的提示信息和时间戳创建倒计时元素,并返回该元素。
function createCountdownElement(promptInput, timestamp, datetimeInput) {
const countdownDiv = document.createElement('p');
countdownDiv.style.backgroundColor = getRandomColor();
const checkboxId = `uniqueCheckbox_${timestamp}`;
// 调用formatDatetime函数格式化datetimeInput
const formattedDatetime = formatDatetime(datetimeInput);
countdownDiv.innerHTML = `
<label for="${checkboxId}"><input type="checkbox" class="uniqueCountdownCheckbox" id="${checkboxId}" value="${timestamp}">
${formattedDatetime}(${promptInput})<b id="倒计时_${timestamp}"></b><button class="finishButton">完成</button></label>
`;
return countdownDiv;
}
// 更新倒计时显示函数:更新指定倒计时元素的显示,包括剩余时间的计算。
function updateCountdownDisplay(elementId, targetDate) {
const countdownElement = document.getElementById(elementId);
const update = () => {
const now = new Date();
const total = targetDate - now;
const timeStr = formatTime(Math.abs(total));
countdownElement.textContent = total <= 0 ? `-${timeStr}` : timeStr;
};
update();
setInterval(update, 1000);
}
// 保存倒计时函数:保存用户输入的倒计时信息,并创建倒计时元素,更新倒计时显示,设置完成按钮事件,清空输入字段。
function saveCountdown() {
const promptInput = document.getElementById('uniquePromptInput').value.trim();
const datetimeInput = document.getElementById('uniqueDatetimeInput').value;
if (promptInput && datetimeInput) {
const targetDate = new Date(datetimeInput);
const timestamp = Date.now();
const countdownElement = createCountdownElement(promptInput, timestamp, datetimeInput);
document.getElementById('uniqueCountdowns').appendChild(countdownElement);
updateCountdown(`倒计时_${timestamp}`, targetDate, promptInput, false);
console.log(`提示信息: ${promptInput}, 目标日期: ${datetimeInput}`);
// 在设置到 localStorage 之前和之后
localStorage.setItem(`倒计时_${timestamp}`, JSON.stringify({ prompt: promptInput, datetime: datetimeInput.replace(/-/g, '').replace(/T/g, '').replace(/:/g, ''), finished: false }));
console.log(`倒计时信息已保存: ${localStorage.getItem(`倒计时_${timestamp}`)}`);
attachFinishButtonEvent(countdownElement, timestamp);
clearInputFields();
} else {
alert('请填写提示信息和目标日期');
}
}
// 格式化时间函数:返回一个字符串,格式为"天:时:分:秒"。
function formatTime(total) {
const seconds = Math.floor((total / 1000) % 60);
const minutes = Math.floor((total / 1000 / 60) % 60);
const hours = Math.floor((total / (1000 * 60 * 60)) % 24);
const days = Math.floor(total / (1000 * 60 * 60 * 24));
return `${days}天${padZero(hours)}:${padZero(minutes)}:${padZero(seconds)}`;
}
document.getElementById('operativeFunction').addEventListener('click', function () {
const button = this;
const finishButtons = document.querySelectorAll('.finishButton');
const countdownCheckboxes = document.querySelectorAll('.uniqueCountdownCheckbox');
toggleOperation(button, finishButtons, countdownCheckboxes);
});
// 清除所选倒计时函数:编辑选中的倒计时,允许用户输入新的提示信息和目标日期。
function editSelectedCountdown() {
const checkboxes = document.querySelectorAll('.uniqueCountdownCheckbox:checked');
if (checkboxes.length === 0) return;
checkboxes.forEach(checkbox => {
const timestamp = checkbox.value;
const data = JSON.parse(localStorage.getItem(`倒计时_${timestamp}`));
if (data) {
const newPrompt = prompt('请输入新的提示信息', data.prompt);
const newDatetime = prompt('目标日期(YYYYMMDDHHMM,例如:202410010400)', data.datetime);
if (newPrompt && newDatetime) {
checkbox.parentNode.remove();
localStorage.setItem(`倒计时_${timestamp}`, JSON.stringify({ prompt: newPrompt, datetime: newDatetime }));
const countdownElement = createCountdownElement(newPrompt, timestamp, newDatetime);
document.getElementById('uniqueCountdowns').appendChild(countdownElement);
updateCountdownDisplay(`倒计时_${timestamp}`, new Date(newDatetime.slice(0, 4), newDatetime.slice(4, 6) - 1, newDatetime.slice(6, 8), newDatetime.slice(8, 10), newDatetime.slice(10, 12)));
}
}
});
checkboxes.forEach(checkbox => checkbox.checked = false);
document.dispatchEvent(new Event('change'));
}
// 删除所选倒计时函数:删除选中的倒计时,确认后从本地存储中移除。
function deleteSelectedCountdown() {
const confirmDelete = confirm("确定要删除选中的倒计时吗?");
if (confirmDelete) {
const checkboxes = document.querySelectorAll('.uniqueCountdownCheckbox:checked');
checkboxes.forEach(checkbox => {
const timestamp = checkbox.value;
localStorage.removeItem(`倒计时_${timestamp}`);
checkbox.parentNode.remove();
});
toggleEditDeleteButtons();
document.dispatchEvent(new Event('change'));
}
}
// 切换操作函数:在操作模式下显示或隐藏,切换按钮文本。
function toggleOperation(button, finishButtons, countdownCheckboxes) {
const isOperating = button.textContent.trim() === '操作';
button.textContent = isOperating ? '取消操作' : '操作';
finishButtons.forEach(finishButton => finishButton.style.display = isOperating ? 'inline-block' : 'none');
countdownCheckboxes.forEach(checkbox => {
checkbox.style.display = isOperating ? 'inline-block' : 'none';
if (!isOperating) checkbox.checked = false;
});
// 显示或隐藏表单
const countdownForm = document.querySelector('.countdown-container');
countdownForm.style.display = isOperating ? 'inline' : 'none'; // 切换显示状态
toggleEditDeleteButtons();
}
// 切换编辑删除按钮函数:根据是否有选中的倒计时,显示或隐藏编辑和删除按钮。
function toggleEditDeleteButtons() {
const isChecked = document.querySelectorAll('.uniqueCountdownCheckbox:checked').length > 0;
document.querySelector('.uniqueEditButton').style.display = isChecked ? 'inline-block' : 'none';
document.querySelector('.uniqueDeleteButton').style.display = isChecked ? 'inline-block' : 'none';
}
document.addEventListener('change', function () {
const checkboxes = document.querySelectorAll('.uniqueCountdownCheckbox');
const finishButtons = document.querySelectorAll('.finishButton');
checkboxes.forEach((checkbox, index) => {
const isChecked = checkbox.checked;
checkbox.style.display = isChecked ? "inline" : "none";
finishButtons[index].style.display = isChecked ? 'inline' : 'none';
});
toggleEditDeleteButtons();
const operativeButton = document.getElementById('operativeFunction');
const isChecked = Array.from(checkboxes).some(checkbox => checkbox.checked);
operativeButton.textContent = isChecked ? '取消操作' : '操作';
});
// 附件完成按钮事件函数:为完成按钮附加事件,切换任务完成状态,并更新本地存储。
function attachFinishButtonEvent(countdownElement, timestamp) {
const finishButton = countdownElement.querySelector('.finishButton');
finishButton.addEventListener('click', () => {
const isFinished = countdownElement.classList.toggle('FinishTask');
finishButton.textContent = isFinished ? '取消' : '完成';
const countdownData = JSON.parse(localStorage.getItem(`倒计时_${timestamp}`));
countdownData.finished = isFinished;
localStorage.setItem(`倒计时_${timestamp}`, JSON.stringify(countdownData));
});
}
// 清空输入字段函数:清空输入框的内容。
function clearInputFields() {
document.getElementById('uniquePromptInput').value = '';
document.getElementById('uniqueDatetimeInput').value = '';
}
// 窗口加载函数:在窗口加载时,读取本地存储中的倒计时数据,并呈现在页面上。
window.onload = function () {
// 检查用户是否已经登录
const countdowns = [];
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key.startsWith('倒计时_')) {
try {
const data = JSON.parse(localStorage.getItem(key));
if (data) {
countdowns.push({ timestamp: key.split('_')[1], data });
}
} catch (error) {
console.error('解析localStorage数据时出错:', error);
}
}
}
countdowns.sort((a, b) => a.timestamp - b.timestamp);
countdowns.forEach(({ timestamp, data }) => {
const countdownElement = createCountdownElement(data.prompt, timestamp, data.datetime);
document.getElementById('uniqueCountdowns').appendChild(countdownElement);
const targetDate = new Date(data.datetime.replace(/(.{4})(.{2})(.{2})(.{2})(.{2})/, "$1-$2-$3T$4:$5"));
updateCountdownDisplay(`倒计时_${timestamp}`, targetDate);
if (data.finished) {
countdownElement.classList.add('FinishTask');
}
attachFinishButtonEvent(countdownElement, timestamp);
});
};
/* 倒计时功能实现 结束*/
</script>
</html>
标签:倒计时,const,timestamp,id,countdown,1px,2px,document,选择器
From: https://blog.csdn.net/lulei5153/article/details/143095234