原生JS倒计时

<!DOCTYPE html>
<html lang="en">

<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>
    #countdown {
      margin-top: 20px;
    }

    #countdown span {
      display: inline-block;
      width: 40px;
      height: 40px;
      line-height: 40px;
      margin-left: 10px;
      margin-right: 10px;
      vertical-align: middle;
      font-size: 16px;
      text-align: center;
      color: white;
      background-color: black;
    }
  </style>
</head>

<body>
  <div>
    <button onclick="init()">获取时间</button>
    <div id="countdown">
      <span id="day"></span><span id="hour"></span>小时
      <span id="min"></span>分钟
      <span id="second"></span></div>
  </div>
  <script>
    function init () {
      getTime() // 点击按钮,先调用一次,避免一秒之后在触发定时器
      setInterval(getTime, 1000)
    }
    function getTime () {
      const newTime = new Date().getTime()
      const loveTime = new Date('2023.01.29 17:05:00').getTime()
      const surplusTime = (loveTime - newTime) / 1000 // 剩余时间秒数
      if (surplusTime > 0) { // 倒计时存在
        var oday = parseInt(surplusTime / 60 / 60 / 24) // 剩余天数
        var ohours = parseInt(surplusTime / 60 / 60 - oday * 24) // 剩余小时数
        var omin = parseInt(surplusTime / 60 - ohours * 60 - oday * 60 * 24) // 剩余分钟数
        var osecond = parseInt(surplusTime - omin * 60 - ohours * 60 * 60 - oday * 60 * 60 * 24) // 剩余秒数
        // 补零
        oday < 10 ? oday = '0' + oday : oday
        ohours < 10 ? ohours = '0' + ohours : ohours
        omin < 10 ? omin = '0' + omin : omin
        osecond < 10 ? osecond = '0' + osecond : osecond
        document.getElementById('day').innerHTML = oday
        document.getElementById('hour').innerHTML = ohours
        document.getElementById('min').innerHTML = omin
        document.getElementById('second').innerHTML = osecond
        //1000表示每隔一秒变化一次,单位为毫秒
      } else {
        document.getElementById('countdown').innerHTML = '情人节快乐🎉'
        clearInterval(getTime)
      }
    }
  </script>
</body>

</html>```

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值