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>Document</title>
<style>
.wrapper {
position: absolute;
left: 50%;
margin-left: -300px;
margin-top: -150px;
top: 50%;
}
.content {
float: left;
width: 200px;
height: 200px;
background-color: black;
color: white;
font-size: 80px;
line-height: 200px;
text-align: center;
border-radius: 50%;
}
.content0 {
float: left;
font-size: 120px;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="content" id="hour">05</div>
<div class="content0">:</div>
<div class="content" id="minture">00</div>
<div class="content0">:</div>
<div class="content" id="second">00</div>
</div>
<script>
var time = 5 * 60 * 60;
var hour, minture, second, timer;
//获取id分别为hour minture second的div
var S = document.getElementById('hour');
var F = document.getElementById('minture');
var M = document.getElementById('second');
//setInterval (callback,time)意思大致为没过time毫秒,执行方法callback
timer = setInterval(
function() {
time -= 1;
normsTime(time);
hour = normsFormat(hour);
minture = normsFormat(minture);
second = normsFormat(second);
//把hour通过S传给html中的id='hour'
S.innerHTML = hour;
F.innerHTML = minture;
M.innerHTML = second;
if (time == 0) {
clearInterval(timer);
alert('时间完了!!!');
}
}, 1000
)
//把秒转化成*小时*分钟*秒
function normsTime(time) {
hour = parseInt(time / 3600);
minture = parseInt(time / 60) - hour * 60;
second = parseInt(time % 60);
}
//规范写法,一般的倒计时时间小于10s的时候都是08或者09啊
function normsFormat(time) {
if (time < 10) {
return '0' + time;
} else {
return time;
}
}
</script>
</body>
</html>