本人小白,本来是想搞个 html 显示当天距离双十一还有 xx 天,使用 html 块输入代码后(代码贴最后)能够显示文字但倒计时计算结果是 0 天,在其他平台测试了能正确显示还有 189 天。有没有大佬告诉一下是啥问题。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>北京时间双十一倒计时</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
margin: 0;
background: linear-gradient(135deg, #ff0036, #ff003690);
font-family: "Microsoft Yahei", sans-serif;
}
.container {
background: rgba(255,255,255,0.95);
padding: 2rem 3rem;
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0,0,0,0.2);
text-align: center;
}
h1 {
color: #ff0036;
margin: 0 0 1rem;
font-size: 2.2em;
}
#countdown {
font-size: 4em;
color: #ff0036;
font-weight: bold;
text-shadow: 2px 2px 5px rgba(0,0,0,0.1);
}
.unit {
font-size: 1.2em;
color: #666;
margin-top: -10px;
}
</style>
</head>
<body>
<div class="container">
<h1>双十一购物狂欢节倒计时</h1>
<div id="countdown">0</div>
<div class="unit">天</div>
</div>
<script>
function getBeijingDayCount() {
// 获取当前UTC时间并转换为北京时间(东八区)
const now = new Date();
const utcNow = now.getTime() + (now.getTimezoneOffset() * 60000);
const beijingNow = new Date(utcNow + (3600000 * 8));
// 创建今年双十一北京时间(11月11日 00:00:00)
let targetYear = beijingNow.getFullYear();
let targetDate = Date.UTC(targetYear, 10, 11 - 1, 16); // 转换为UTC时间:11月10日16时(即北京时间11日0时)
// 如果已过今年双十一,计算明年
if (beijingNow >= new Date(targetDate + 86400000)) {
targetDate = Date.UTC(targetYear + 1, 10, 11 - 1, 16);
}
// 计算剩余天数(按完整自然日计算)
const diff = targetDate - beijingNow.getTime();
return Math.floor(diff / 86400000);
}
function updateDisplay() {
const days = getBeijingDayCount();
document.getElementById('countdown').textContent = days;
document.title = `还剩${days}天 - 双十一倒计时`;
}
// 初始化并设置定时器
updateDisplay();
setInterval(updateDisplay, 60000); // 每分钟更新保证跨日准确
</script>
</body>
</html>