JavaScript函数——倒计时效果

本文介绍如何利用JavaScript创建倒计时效果,包括HTML结构布局、CSS样式设计以及JavaScript核心逻辑实现,帮助读者理解动态更新时间的原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

<!DOCTYPE html>
<html lang="zh-cn">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>倒计时</title>
    <style>
      body {
        font-family: tenxunti;
        box-sizing: border-box;
        margin: 0;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
      }
      @font-face {
        font-family: tenxunti;
        src: url(fonts/腾讯体.ttf);
      }
      .cutdown {
        width: 300px;
        height: 400px;
        background-color: #df2b1f;
        padding: 0px 20px;
        text-align: center;
        color: white;
        font-size: 25px;
        border-radius: 10px;
      }

      .cutdown h3 {
        padding: 5px;
        margin: 100px 0 20px 0;
      }
      .cutdown span {
        display: inline-block;
        width: 50px;
        padding: 10px 5px;
        background-color: #2f3430;
      }
    </style>
  </head>
  <body>
    <div class="cutdown">
      <h3>Remaining Time</h3>
      <span>D</span>
      :
      <span>H</span>
      :
      <span>M</span>
      :
      <span>S</span>
    </div>
  </body>
  <script>
    let cutDHMS = document.querySelectorAll("span");
    function countDown(time) {
      setInterval(function () {
        let nowTime = +new Date(); //返回当前毫秒数
        let inputTime = +new Date(time); //返回输入毫秒数
        let times = (inputTime - nowTime) / 1000; //剩余时间秒数
        let d = parseInt(times / 60 / 60 / 24); //天
        d = d < 10 ? "0" + d : d;
        let h = parseInt((times / 60 / 60) % 24); //时
        h = h < 10 ? "0" + h : h;
        let m = parseInt((times / 60) % 60); //分
        m = m < 10 ? "0" + m : m;
        let s = parseInt(times % 60); //秒
        s = s < 10 ? "0" + s : s;
        let DHMS = [d, h, m, s];
        for (let i = 0; i < cutDHMS.length; i++) {
          cutDHMS[i].innerHTML = DHMS[i];
        }
      }, 1000);
    }
    countDown("2022-5-20 00:00:00");
  </script>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值