<style type="text/css">
div{ width:200px; height:100px; background-color:black; margin:0 auto; padding-top:20px;color:#fff;font-family:"微軟雅黑"; text-align:center;}
span{ background:#fff; margin:20px;color:#000;}
button{ width:160px; height:40px;background:green;color:#fff; outline:none; border:none; border-radius:10px; margin:20px 0 0 0;}
</style>
</head>
<body>
<div>
<span>01</span>分鐘<span>40</span>秒
<button type="button">啓動</button>
</div>
<script type="text/javascript">
var btn=document.getElementsByTagName("button");
var spans=document.getElementsByTagName("span");
btn[0].addEventListener("click",function(){
function changeTime(){
var time0=parseInt(spans[0].childNodes[0].nodeValue);//獲取文本節點中的字符串並將其轉化爲數字
var time1=parseInt(spans[1].childNodes[0].nodeValue);
if(time1>0){
time1 --;
spans[1].innerHTML = time1;
}
else if(time1==0&&time0!=0){
spans[0].innerHTML = 0;
spans[1].innerHTML = 60;
time1=parseInt(spans[1].childNodes[0].nodeValue);//重新寫入span[0]之後,time1發生改變,需要再獲取一次
}
else if(time1==0&&time0==0){
clearInterval(clear);
}
}
if(btn[0].innerHTML=="啓動"){
clear=setInterval(changeTime,1000);
btn[0].style.background="red";
btn[0].innerHTML="取消";
}
else{
clearInterval(clear);
btn[0].style.background="green";
btn[0].innerHTML="啓動";
}
},false);
</script>
</body>
說明:該項目中需要注意的是定時器函數中的條件變化
源碼:
<style>
body,div{margin:0;padding:0;}
body{color:#fff;font:16px/1.5 \5fae\8f6f\96c5\9ed1;}
#countdown{width:300px;text-align:center;background:#1a1a1a;margin:10px auto;padding:20px 0;}
input{border:0;width:283px;height:50px;cursor:pointer;margin-top:20px;background:url(img/btn-1.png) no-repeat;}
input.cancel{background-position:0 -50px;}
span{color:#000;width:80px;line-height:2;background:#fbfbfb;border:2px solid #b4b4b4;margin:0 10px;padding:0 10px;}
</style>
<script>
window.onload = function ()
{
var oCountDown = document.getElementById("countdown");
var aInput = oCountDown.getElementsByTagName("input")[0];
var timer = null;
aInput.onclick = function ()
{
this.className == "" ? (timer = setInterval(updateTime, 1000), updateTime()) : (clearInterval(timer));
this.className = this.className == '' ? "cancel" : '';
};
function format(a)
{
return a.toString().replace(/^(\d)$/,'0$1')
}
function updateTime ()
{
var aSpan = oCountDown.getElementsByTagName("span");
var oRemain = aSpan[0].innerHTML.replace(/^0/,'') * 60 + parseInt(aSpan[1].innerHTML.replace(/^0/,''));
if(oRemain <= 0)
{
clearInterval(timer);
return
}
oRemain--;
aSpan[0].innerHTML = format(parseInt(oRemain / 60));
oRemain %= 60;
aSpan[1].innerHTML = format(parseInt(oRemain));
}
}
</script>
</head>
<body>
<div id="countdown">
<span>01</span>分鐘<span>40</span>秒
<input type="button" value="" />
</div>
</body>