You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现按当日实时时间动态更新的网站维护进度条?

实现按当日实时时间动态显示维护进度条

当然可以实现这个需求,核心思路是计算当前时刻在一天总时长中的占比,以此作为进度条的百分比。以下是修改后的完整代码:

完整代码

HTML

<body class="bg">
  <div class="hours"></div>
  <div class="minutes"></div>
  <div class="seconds"></div>
  <br><br>
        
  <div class="progress-wrapper">
    <div class="progress">
      <span>0%</span>
    </div>
  </div>
</body>

CSS

.bg {background:#08093cb3;}

.hours, .minutes, .seconds {
  float: left; 
  font-size: 1.5em;
  color: #008c8c;
}

.progress-wrapper {
  width: 100%;
  background: #222;
  display: flex;
  margin-bottom: 20px;
  border-radius: 5px;
}
        
.progress {
  width: 0%;
  height: 10px;
  background: green;
  border-radius: 5px;
  display: flex;
  justify-content: flex-end;
}
        
.progress span {
  color: white;
  position: relative;
  top: 13px;
  left: 25px;
  font-weight: 800;
}

JavaScript

const hoursEl = document.querySelector(".hours");
const minutesEl = document.querySelector(".minutes");
const secondsEl = document.querySelector(".seconds");
const progress = document.querySelector('.progress');
const percentage = document.querySelector('.progress span');

// 一天总秒数:24*60*60
const totalSecondsInDay = 86400;

function updateTimeAndProgress() {
  const today = new Date();
  let hr = today.getHours();
  let min = today.getMinutes();
  let sec = today.getSeconds();

  // 格式化时间显示(补零)
  hr = hr < 10 ? `0${hr}` : hr;
  min = min < 10 ? `0${min}` : min;
  sec = sec < 10 ? `0${sec}` : sec;

  // 更新时间文本
  hoursEl.textContent = `${hr} : `;
  minutesEl.textContent = `${min} : `;
  secondsEl.textContent = sec;

  // 计算进度百分比
  const elapsedSeconds = hr * 3600 + min * 60 + sec;
  const progressPercent = (elapsedSeconds / totalSecondsInDay) * 100;
  // 保留1位小数,如需更精确可调整小数位数
  const formattedPercent = progressPercent.toFixed(1);

  // 更新进度条和百分比显示
  progress.style.width = `${formattedPercent}%`;
  percentage.textContent = `${formattedPercent}%`;
}

// 每500毫秒更新一次(和原时间更新频率一致)
setInterval(updateTimeAndProgress, 500);

关键逻辑说明

  1. 进度计算核心:通过elapsedSeconds = 小时*3600 + 分钟*60 + 秒得到当日已过的总秒数,除以一天的总秒数86400后乘以100,得到当前进度百分比。
  2. 精度控制:使用toFixed(1)保留1位小数,满足精确显示需求(例如18:15时,计算结果为≈76.0%,完全符合实时占比)。
  3. 性能优化:将时间显示和进度更新合并到一个函数中,避免多个定时器重复执行,提升页面运行效率。

内容的提问来源于stack exchange,提问作者PC12345

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 03:36:30