本文實(shí)例為大家分享了js實(shí)現(xiàn)簡(jiǎn)單的秒表具體代碼,供大家參考,具體內(nèi)容如下

描述:
實(shí)現(xiàn)一個(gè)簡(jiǎn)單的秒表,點(diǎn)擊啟動(dòng)按鈕時(shí)開始計(jì)時(shí),隨后啟動(dòng)按鈕變?yōu)闀和#?/p>
點(diǎn)擊暫停暫停計(jì)時(shí),點(diǎn)擊復(fù)位回到最初始狀態(tài)。
效果:
代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#showTime
{
width: 300px;
height: 60px;
font-size: 60px;
line-height: 60px;
}
</style>
</head>
<body>
<div>
<div id="showTime">00:00:00</div>
<button id="startBn">啟動(dòng)</button>
<button id="restBn">復(fù)位</button>
</div>
<script>
//——————
var time,showTime,startBn,restBn,pauseDate;
//布爾開關(guān)
var bool=false;
//暫停的累計(jì)時(shí)間
var pauseTime=0;
init();
function init() {
showTime=document.getElementById("showTime");
startBn=document.getElementById("startBn");
restBn=document.getElementById("restBn");
startBn.addEventListener("click",clickHandler);//開始按鈕 ~ 暫停按鈕
restBn.addEventListener("click",clickHandler);//復(fù)位按鈕
setInterval(animation,16);
}
//轉(zhuǎn)化時(shí)間函數(shù)
function animation() {
if(!bool) return;
//前時(shí)間減去上次開啟時(shí)間減去暫停累計(jì)時(shí)間
var times=new Date().getTime()-time-pauseTime;
var minutes=Math.floor(times/60000);//毫秒轉(zhuǎn)化為分鐘
var seconds=Math.floor((times-minutes*60000)/1000);//已知分鐘
將time減去分鐘 除去1000得出 秒
var ms=Math.floor((times-minutes*60000-seconds*1000)/10);//
showTime.innerHTML=
(minutes<10 ? "0" +minutes : minutes)+":"
+(seconds<10 ? "0"+seconds :seconds)+":"
+(ms<10 ? "0"+ms : ms);
}
//點(diǎn)擊時(shí)的事件
function clickHandler(e) {
e= e || window.event;
if(this===startBn){
bool=!bool;
if(bool){
this.innerHTML="暫停";
//如果我們上一次暫停時(shí)間是空,表示沒有暫停過,因此,直接返回0
//如果上次的暫停時(shí)間是有值得,用當(dāng)前毫秒數(shù)減去上次的毫秒數(shù),這樣就會(huì)得到暫停時(shí)間
pauseTime+=(!pauseDate ? 0 : new Date().getTime()-pauseDate);
if(time) return;
time=new Date().getTime();
return;//是為bool判斷跳出
}
this.innerHTML="啟動(dòng)";
pauseDate=new Date().getTime();
return;//是為this是否等于startBn判斷跳出
}
startBn.innerHTML="啟動(dòng)";
pauseTime=0;
pauseDate=null;
bool=false;
time=0;
showTime.innerHTML="00:00:00";
}
</script>
</body>
</html>
標(biāo)題名稱:js實(shí)現(xiàn)簡(jiǎn)單的秒表-創(chuàng)新互聯(lián)
標(biāo)題來源:http://chinadenli.net/article6/didgog.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供ChatGPT、定制開發(fā)、建站公司、網(wǎng)站維護(hù)、定制網(wǎng)站、網(wǎng)站收錄
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容