如图所示,该倒计时分为上下两个部分,上面是选择要设置的时间,下面是显示倒计时
这是CSS部分代码:
*{
margin: 0;
padding: 0;
}
body{
text-align: center;
}
#time_choose{
margin-top: 60px;
}
select{
150px;
color: #333;
border-radius: 5px;
padding: 6px 12px;
}
label{
margin-right: 10px;
}
button{
padding: 6px 12px;
cursor: pointer;
border: none;
outline: none;
border-radius: 4px;
color: white;
}
.start{
background: red;
}
.reset{
background-color: blue;
}
#time_show{
display: flex;
justify-content: center;
margin-top: 100px;
}
#time_show>div{
120px;
height: 200px;
margin: 0 20px;
font-size: 120px;
}
#time_show .dot{
30px;
}
body部分:
<div id="time_choose">
<select name="" id="hour"></select>
<label for="hour">时</label>
<select name="" id="min"></select>
<label for="min">分</label>
<select name="" id="sec"></select>
<label for="sec">秒</label>
<button type="button" class="start">开始</button>
<button type="button" class="reset">重置</button>
</div>
<div id="time_show">
<div class="time hour_show">00</div>
<div class="dot">:</div>
<div class="time min_show">00</div>
<div class="dot">:</div>
<div class="time sec_show">00</div>
</div>
script部分:
//利用函数为不同的区域添加内容
var hour = document.getElementById('hour');
var min = document.getElementById('min');
var sec = document.getElementById('sec');
//分别为时、分、秒添加下拉框
for(var i =0 ; i <=24 ; i++){
hour.innerHTML +=`<option value ="${i}">${i}</option>`;
}
for(var i =0 ; i <=60 ; i++){
min.innerHTML +=`<option value ="${i}">${i}</option>`;
}
for(var i =0 ; i <=60 ; i++){
sec.innerHTML +=`<option value ="${i}">${i}</option>`;
}
var start = document.querySelector('.start');
var reset = document.querySelector('.reset');
var time = null;
start.onclick = function(){
//获取当前的值
var h = hour.value;
var m = min.value;
var s = sec.value;
//总秒数
var total = parseInt(h * 3600 + m * 60 + s * 1);
readerTime(total);
time = setInterval(function(){
if(total ==0){ //做个判断
clearInterval(time);
reset1();
alert('时间到!');
return;
}
total = total-1;
readerTime(total);
},1000)
}
reset.onclick = reset1;
//不满2位在前面添加0
function readerTime(num){
var h = parseInt(num / 3600).toString().padStart(2,'0');
var m = parseInt((num - h*3600)/60).toString().padStart(2,'0');
var s = parseInt(num%60).toString().padStart(2,'0');
document.querySelector('.hour_show').innerHTML = h;
document.querySelector('.min_show').innerHTML = m;
document.querySelector('.sec_show').innerHTML = s;
}
function reset1(){
clearInterval(time);
//设置为初始值0
hour.value = 0;
min.value = 0;
sec.value = 0;
readerTime(0);
}