一、代码

<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body {
            text-align: center;
            background-color: #333333;
            color: #66ff66;
        }
        h1 {
            font-size: 40px; /* 字体大小 */
            text-align: center; /* 文本居中 */
            position: absolute; /* 绝对定位 */
            top: 25%;
            left: 50%;
            transform: translate(-50%, -50%); /* 定位调整 */
        }
        /* 设置倒计时样式 */
        #countdown {
            font-size: 75px; /* 字体大小 */
            text-align: center; /* 文本居中 */
            position: absolute; /* 绝对定位 */
            top: 50%; /* 顶部位置 */
            left: 50%; /* 左侧位置 */
            transform: translate(-50%, -50%); /* 定位调整 */
        }
    </style>
    <title>2035年倒计时</title>
</head>
<body>
<h1>2035年倒计时</h1>
<div id="countdown"></div>
<script>
    // 设置目标日期
    const targetDate = new Date('2035-01-01T00:00:00').getTime();

    /**
     * 计算并显示倒计时
     * 该函数无参数和返回值
     */
    function countdown() {
        const now = new Date().getTime(); // 获取当前时间戳
        const distance = targetDate - now; // 计算目标时间与当前时间的差值

        // 计算天、小时、分钟和秒
        const days = Math.floor(distance / (1000 * 60 * 60 * 24));
        const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((distance % (1000 * 60)) / 1000);

        // 在倒计时元素中显示结果
        document.getElementById("countdown").innerText = `${days}${hours} 小时 ${minutes} 分钟 ${seconds}`;

        // 每秒调用一次该函数以更新倒计时
        setTimeout(countdown, 1000);
    }

    // 启动倒计时
    countdown();
</script>
</body>
</html>

二、解释

这段HTML代码定义了一个简单的网页,用于显示到2035年的倒计时。以下是该网页的基本结构和功能的详细解释:

DOCTYPE声明:

<!DOCTYPE html> 表明这是遵循HTML5标准的文档。
html标签:<html lang="zh-cn"> 定义了整个HTML文档,并指定了语言为中文。

head部分:

<meta charset="UTF-8"> 指定网页字符编码为UTF-8。
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 设置响应式布局,确保页面在不同设备上自适应显示。
<style> 标签内包含CSS样式,对body、h1和id为countdown的元素进行样式设置,如背景颜色、文本颜色、居中显示以及定位等。
title标签:定义了浏览器标签页上的网页标题——“2035年倒计时”。

body部分:

<h1>2035年倒计时</h1> 在网页主体中添加一个一级标题,显示“2035年倒计时”。
<div id="countdown"></div> 创建一个空div元素,其id为"countdown",用于动态显示倒计时信息。

script标签:

JavaScript代码段实现倒计时功能:
定义目标日期 const targetDate = new Date('2035-01-01T00:00:00').getTime();
countdown 函数负责计算当前距离目标日期的时间差,并以天、小时、分钟和秒的形式显示在id为 “countdown” 的div中。
使用 setTimeout(countdown, 1000) 实现每秒更新一次倒计时。
当用户打开这个网页时,将启动倒计时函数并实时显示距离2035年1月1日00:00:00剩余的天数、小时数、分钟数和秒数。同时,网页整体风格采用深灰色背景与亮绿色字体,所有内容居中显示。

03-12 16:45