分享

基于HTML、CSS和JavaScript制作一个中秋节倒计时网页

 海拥 2023-09-14 发布于安徽

这个项目使用HTML、CSS和JavaScript来制作一个简单但有趣的中秋节倒计时网页。网页将显示距离中秋节还有多少天、小时、分钟和秒,并添加一些中秋节相关的图像和祝福语。

在线预览地址:https:///demo/zhongqiu/

1. HTML 结构

首先,创建一个HTML文件,命名为 index.html,并在其中添加以下基本结构:

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>中秋节倒计时</title><link rel="stylesheet" href="style.css"></head><body><div class="countdown-container"><h1>中秋节倒计时</h1><div id="countdown"></div><div class="greetings"><img src="moon.png" alt="月亮图像"><p>祝你中秋节快乐!</p></div></div><script src="script.js"></script></body></html>

2. CSS 样式

创建一个名为 style.css 的 CSS 文件,并添加样式来美化页面,代码如下:

body {font-family: Arial, sans-serif;background-color: #f2f2f2;text-align: center;}.countdown-container {background-color: #fff;border-radius: 10px;padding: 20px;box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);margin: 50px auto;max-width: 400px;}h1 {font-size: 24px;margin-bottom: 10px;}#greetings {margin-top: 20px;}img {width: 128px;height: 96px;}p {font-size: 18px;font-weight: bold;}

3. JavaScript 倒计时

创建一个名为 script.js 的 JavaScript 文件,来实现倒计时功能。

// 中秋节日期(年/月/日)const midAutumnDate = new Date('2023-09-29T00:00:00');function updateCountdown() {// 获取当前时间const now = new Date();// 计算距离中秋节的时间差(毫秒)const timeRemaining = midAutumnDate - now;// 计算天数、小时、分钟和秒数const days = Math.floor(timeRemaining / (1000 * 60 * 60 * 24));const hours = Math.floor((timeRemaining % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));const minutes = Math.floor((timeRemaining % (1000 * 60 * 60)) / (1000 * 60));const seconds = Math.floor((timeRemaining % (1000 * 60)) / 1000);// 更新页面上的倒计时元素document.getElementById('countdown').innerHTML = `${days} 天 ${hours} 小时 ${minutes} 分钟 ${seconds} 秒`;}// 每秒调用一次updateCountdown函数,以实时更新倒计时setInterval(updateCountdown, 1000);// 初次加载页面时立即更新倒计时updateCountdown();

这段JavaScript代码执行以下操作:

  • 创建一个JavaScript日期对象 midAutumnDate,表示中秋节的日期和时间(今年中秋节是2023年9月29日)。

  • 定义一个名为 updateCountdown 的函数,用于计算并更新倒计时。它执行以下步骤:

    • 获取当前时间,存储在 now 变量中。

    • 计算距离中秋节的时间差(以毫秒为单位),存储在 timeRemaining 变量中。

    • 使用数学函数计算剩余的天数、小时、分钟和秒数。

    • 更新网页上的倒计时元素,将计算得到的时间显示在页面上。

  • 使用 setInterval 函数每秒调用一次 updateCountdown 函数,以实时更新倒计时。

  • 在页面加载时,立即调用 updateCountdown 函数,以确保初次加载时显示正确的倒计时。

4. 图像

我们需要一张月亮的图像,将其命名为 moon.png,并放在项目目录下。
在这里插入图片描述

5. 运行

将以上三个文件放在同一个目录下,然后打开 midAutumnCountdown.html 文件,我们可以看到一个漂亮的中秋节倒计时页面,页面上会显示距离中秋节的时间,以及中秋节的祝福语和月亮图像。

在这里插入图片描述

这个简单的项目展示了如何使用HTML、CSS和JavaScript来创建一个与中秋节相关的网页,让我们可以随时了解距离中秋节还有多少时间。大家可以根据自己的创意和技能进一步扩展这个项目,添加更多功能和效果,以增加中秋节的乐趣。最后,提前祝大家中秋节快乐!

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多