首次参加csdn的活动“提交一个元旦倒计时代码”,纪念一下。
使用了setInterval函数传递第三个参数,IE9以及以下版本不支持。
<!doctype html>
<html>
<head>
<script type="text/javascript">
var showCountDown = function(dateStr) {
var toDate,nowDate,toTime,nowTime;
var diff,ms,seconde,minute,hour,day;
var str;
toDate = new Date(dateStr);
nowDate = new Date();
toTime = toDate.getTime();
nowTime = nowDate.getTime();
diff = toTime - nowTime;
if(diff > 0) {
//console.log(diff);
ms = Math.floor(diff % 1000);
//console.log('ms: ' + ms);
diff = diff / 1000;
second = Math.floor(diff % 60 );
diff = diff / 60;
minute = Math.floor(diff % 60);
diff = diff / 60;
hour = Math.floor(diff % 24);
diff = diff / 24;
day = Math.floor(diff % 24);
document.getElementById('day').innerHTML = day + "天";
document.getElementById('hour').innerHTML = hour + "小时";
document.getElementById('minute').innerHTML = minute + "分钟";
document.getElementById('second').innerHTML = second + "秒";
}
else {
alert('倒计时已结束!');
}
}
function init() {
showCountDown("2023-1-1 00:00:00");
setInterval(showCountDown,1000,"2023-1-1 00:00:00");
}
</script>
<style>
body{
text-align: center;
}
div {
display:inline-block;
}
span{
float: left;
font-size: 50px;
}
label {
float: left;
width: 100px;
height: 100px;
background-color: #000;
line-height: 100px;
color: #fff;
font-size: 30px;
margin-right: 10px;
text-decoration:none;
}
</style>
</head>
<body onload="init()">
<h1 style="color:red;">
元旦倒计时
</h1>
<div>
<span>
<label id="day">
</label>
<label id="hour">
</label>
<label id="minute">
</label>
<label id="second">
</label>
</span>
</div>
</body>
</html>