學(xué)習(xí)資料
http://v.apelearn.com/student.php
要求
通過(guò)點(diǎn)擊不同的按鈕實(shí)現(xiàn)一個(gè)簡(jiǎn)單計(jì)時(shí)器的啟動(dòng)睛琳、暫停杂腰、復(fù)位的效果;
知識(shí)點(diǎn)
1.時(shí)間的計(jì)算: 參考http://www.reibang.com/p/5e57c715284a
2.小于10的時(shí)分秒的顯示方式昨悼;
3.定時(shí)器setInterval()的使用及清除定時(shí)器clearInterval(timer);
實(shí)現(xiàn)思路
開(kāi)始計(jì)時(shí)
1.獲取開(kāi)始按鈕捣辆,計(jì)時(shí)器容器换况,定義一個(gè)變量要存儲(chǔ)時(shí)間(defaultTime)欠气;
2.給開(kāi)始按鈕綁定點(diǎn)擊事件厅各;
3.使用定時(shí)器setInterval(),每個(gè)一秒執(zhí)行一次定時(shí)器中的回調(diào)函數(shù);
4.在定時(shí)器回調(diào)函數(shù)中,每執(zhí)行一次预柒,存儲(chǔ)時(shí)間的變量defaultTime自增1队塘,計(jì)算小時(shí);
5. 使用計(jì)算小時(shí)候剩余的時(shí)間來(lái)計(jì)算分鐘數(shù)宜鸯,以及秒數(shù)憔古;
6.將得到的時(shí)分秒的整合值作為時(shí)間容器的內(nèi)容;
demo代碼
HTML
<div class="timer">
<h2>簡(jiǎn)易定時(shí)器</h2>
<div class="btn-group">
<button class="btn btn1">start</button>
<button class="btn btn2">pause</button>
<button class="btn btn3">counter</button>
<button class="btn btn4">reset</button>
</div>
</div>
CSS
.timer{width:600px;height:300px;margin:30px auto;background:#eee;padding:10px 15px;}
.btn-group{width:100%;height:34px;line-height:34px;}
.btn{width:60px;height:34px;line-height:34px;text-align:center;border:none;outline:none;background:#00a0e6;border-radius:5px;color:#fff;margin-right:10px;}
.time,.save-time{width:100%;height:60px;line-height:60px;margin-top:10px;background:bisque;text-align:center;border-radius:5px;color:#666;}
JS
var defaultTime =0;
vartimer =null;
varhours,minutes,seconds,liftTime,time;
/*
* 點(diǎn)擊開(kāi)始按鈕淋袖,每個(gè)一秒執(zhí)行一次回調(diào)函數(shù)
* 開(kāi)始計(jì)時(shí)
*/
$('.btn1').click(function() {
timer =setInterval(function() {
defaultTime++;
//有多少小時(shí)
hours =parseInt(defaultTime / (60*60));
//計(jì)算小時(shí)候剩余的時(shí)間
liftTime = defaultTime % (60*60);
//多少分鐘
minutes =parseInt(liftTime /60);
//秒
seconds =parseInt(liftTime %60);
time = (hours >9? hours :'0'+ hours) +':'
+ (minutes >9? minutes :'0'+ minutes) +':'
+ (seconds >9? seconds :'0'+ seconds);
$('.time').html(time);
},1000)
});
/*
* 暫停
*/
$('.btn2').click(function() {
clearInterval(timer);
});
/*
* 暫存某一時(shí)刻的時(shí)間
*/
$('.btn3').click(function() {
$('.save-time').html(time);
});
/*
* 復(fù)位
*/
$('.btn4').click(function() {
clearInterval(timer);
$('.time').html('00:00:00');
});
暫停定時(shí)
清除定時(shí)器
復(fù)位
清除定時(shí)器鸿市,并將定時(shí)器容器的內(nèi)容設(shè)置為: 00:00:00