用HTML实现一个倒计时的进度条,目前只实现了进度条,没有实现时钟格式的文本显示
创建页面
创建一个包含基本元素的页面,包含文本提示,进度条,功能按钮。使用了Bootstrap5组件,源码如下
<!DOCTYPE html>
<html lang="zh-Hans-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">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
<title>倒计时</title>
</head>
<body>
<div class="container">
<br>
<h1 id="hh1">倒计时DEMO!</h1>
<div class="progress" role="progressbar" aria-valuemin="0" aria-valuemax="100" style="height: 25px">
<div class="progress-bar progress-bar-striped progress-bar-animated" style="width: 100%">100%</div>
</div>
<br>
<button id="btn1" type="button" class="btn btn-primary">click me</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ENjdO4Dr2bkBIFxQpeoTz1HIcje39Wm4jDKdf19U8gI4ddQ3GYNS7NTKfAdVQSZe"
crossorigin="anonymous"></script>
</body>
</html>
添加按钮功能
给按钮添加事件处理,并在事件处理中启动计时函数的调用
<button id="btn1" type="button" class="btn btn-primary" onclick="timecnt()">click me</button>
JS方法如下
<script>
let t1,timerhandle;
let time_status = false;
function timecnt() {
t1 = +new Date();
if(time_status==false){
timerhandle = setInterval(倒计时方法,1000);
btn1.innerHTML = "stop"
btn1.className = 'btn btn-danger';
}else{
clearInterval(timerhandle);
btn1.innerHTML = "Click me";
btn1.className = 'btn btn-primary';
}
time_status = !time_status;
}
</script>
完成计时方法
该方法被周期调用,与t1进行时间计算,得出时间间隔,根据时间间隔控制页面元素,方法如下
function dida(){
let t2 = +new Date();
let timer = parseInt((t2-t1)/100);
hh1.innerHTML = "timer:" + timer;
let leftstr = (100-timer)+'%';
let bar = document.getElementsByClassName('progress-bar')[0];
bar.style.width = leftstr;
bar.innerHTML = leftstr;
if(timer>=100){
clearInterval(timerhandle);
btn1.innerHTML = "Game Over";
btn1.className = 'btn btn-secondary';
hh1.innerHTML = '倒计时结束';
}
}
修改调用为
timerhandle = setInterval(dida,1000);
后记
使用let t1 = +new Date()
可以获得当前时间的毫秒表示值,在计算时间间隔时直接/100是按每秒10%的进度处理,如果让进度变慢或更快,调整除数即可。
此例仅实现了基本的功能,后续可考虑在进度条上加入时间格式串的显示。