文章目录

  • 基于HTML实现2023年倒计时
    • 代码实现

基于HTML实现2023年倒计时

代码实现

<!DOCTYPE html><html><head><meta charset="utf-8"><title>2023倒计时</title><style>  /* 公共基础样式 */  #clockdiv{    width: 300px;    height: 300px;    background-color: #14274F;    color: #fff;    display: flex;    justify-content: center;    align-items: center;    margin: 50px;  }  /* 凸起效果样式 */  #demo1 {    border-left: 1px solid #33B8EC;    border-top: 1px solid #33B8EC;    border-right: 3px solid #000;    border-bottom: 3px solid #000;    color: #ffffff;      }</style></head><body><div id="clockdiv">  <div id="demo1">    <div>      <div >距离2023年元旦还有</div>    </div>    <div>      <span class="days">0</span>      <div class="smalltext"></div>    </div>    <div>      <span class="hours">0</span>      <div class="smalltext">小时</div>    </div>    <div>      <span class="minutes">0</span>      <div class="smalltext"></div>    </div>    <div>      <span class="seconds">0</span>      <div class="smalltext"></div>    </div>  </div></div><script>// 设定结束时间var deadline = new Date("2023-01-01 00:00:00").getTime();// 每秒更新倒计时var x = setInterval(function() {  // 获取当前时间  var now = new Date().getTime();  // 计算时间差  var t = deadline - now;  // 计算天、小时、分钟、秒  var days = Math.floor(t / (1000 * 60 * 60 * 24));  var hours = Math.floor((t % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));  var minutes = Math.floor((t % (1000 * 60 * 60)) / (1000 * 60));  var seconds = Math.floor((t % (1000 * 60)) / 1000);  // 显示倒计时  document.getElementsByClassName("days")[0].innerHTML = days;  document.getElementsByClassName("hours")[0].innerHTML = hours;  document.getElementsByClassName("minutes")[0].innerHTML = minutes;  document.getElementsByClassName("seconds")[0].innerHTML = seconds;  // 如果结束时间到了,停止倒计时  if (t < 0) {    clearInterval(x);    document.getElementById("clockdiv").innerHTML = "倒计时结束";  }}, 1000);</script></body></html>

输出为: