溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

js實(shí)現(xiàn)簡單的秒表效果的代碼分享

發(fā)布時(shí)間:2020-04-02 10:54:18 來源:億速云 閱讀:325 作者:小新 欄目:web開發(fā)

今天小編給大家分享的是js實(shí)現(xiàn)簡單的秒表效果的代碼,很多人都不太了解,今天小編為了讓大家更加容易的實(shí)現(xiàn)簡單的秒表效果,所以給大家總結(jié)了以下內(nèi)容,一起往下看吧。一定會(huì)有所收獲的哦。

js實(shí)現(xiàn)簡單的秒表效果的代碼分享

描述:

實(shí)現(xiàn)一個(gè)簡單的秒表,點(diǎn)擊啟動(dòng)按鈕時(shí)開始計(jì)時(shí),隨后啟動(dòng)按鈕變?yōu)闀和#?/p>

點(diǎn)擊暫停暫停計(jì)時(shí),點(diǎn)擊復(fù)位回到最初始狀態(tài)。

效果:

js實(shí)現(xiàn)簡單的秒表效果的代碼分享

代碼如下:

<!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>

關(guān)于js實(shí)現(xiàn)簡單的秒表效果的代碼就分享到這里了,當(dāng)然并不止以上和大家分析的辦法,不過小編可以保證其準(zhǔn)確性是絕對沒問題的。希望以上內(nèi)容可以對大家有一定的參考價(jià)值,可以學(xué)以致用。如果喜歡本篇文章,不妨把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI