- <html>
- <head>
- <title>倒计时</title>
- <!–以下为css样式–>
- <style type= “text/css”>
- .daojishi h2
- {
- font-family:Helvetica, Microsoft YaHei, Arial, sans-serif;
- font-size:14px;
- margin-bottom:5px;
- color:#151515;
- }
- .daojishi #timer
- {
- font-family:Helvetica, Microsoft YaHei, Arial, sans-serif;
- font-size:14px;
- color:#151515;
- font-weight:bold;
- }
- </style>
- <script type = “text/javascript” src = “timer.js”>
- </script>
- </head>
- <body onload = “timer()”>
- <div class = “daojishi”>
- <h2>剩余时间为:</h2>
- <div id = “timer”>
- </div>
- </div>
- </body>
- </html>
timer.js
- function timer()
- {
- var ts = (new Date(2018, 11, 11, 9, 0, 0)) – (new Date());//计算剩余的毫秒数
- var dd = parseInt(ts / 1000 / 60 / 60 / 24, 10);//计算剩余的天数
- var hh = parseInt(ts / 1000 / 60 / 60 % 24, 10);//计算剩余的小时数
- var mm = parseInt(ts / 1000 / 60 % 60, 10);//计算剩余的分钟数
- var ss = parseInt(ts / 1000 % 60, 10);//计算剩余的秒数
- dd = checkTime(dd);
- hh = checkTime(hh);
- mm = checkTime(mm);
- ss = checkTime(ss);
- document.getElementById(“timer”).innerHTML = dd + “天” + hh + “时” + mm + “分” + ss + “秒”;
- setInterval(“timer()”,1000);
- }
- function checkTime(i)
- {
- if (i < 10) {
- i = “0” + i;
- }
- return i;
- }
一个页面中有多个倒计时
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” ” http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=” http://www.w3.org/1999/xhtml”>
<head>
<title>Timer – by Vilic JavaScriptQQ交流群56484577</title>
</head>
<body>
<div id=”timer1″></div>
<div id=”timer2″></div>
<div id=”timer3″></div>
</body>
<script type=”text/javascript”>
var addTimer = function () {
var list = [],
interval;
return function (id, time) {
if (!interval)
interval = setInterval(go, 1000);
list.push({ ele: document.getElementById(id), time: time });
}
function go() {
for (var i = 0; i < list.length; i++) {
list[i].ele.innerHTML = getTimerString(list[i].time ? list[i].time -= 1 : 0);
if (!list[i].time)
list.splice(i–, 1);
}
}
function getTimerString(time) {
var not0 = !!time,
d = Math.floor(time / 86400),
h = Math.floor((time %= 86400) / 3600),
m = Math.floor((time %= 3600) / 60),
s = time % 60;
if (not0)
return “还有” + d + “天” + h + “小时” + m + “分” + s + “秒”;
else return “时间到”;
}
} ();
addTimer(“timer1”, 12);
addTimer(“timer2”, 10);
addTimer(“timer3”, 13);
</script>
</html>