DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> HTML基礎知識 >> HTML5教程
用 HTML5 打造簡單計時器:專注與休息的平衡小工具
編輯:HTML5教程     

計時器不一定只能寫在 JavaScript 裡;結合 HTML5 的 canvas、表單輸入與 setInterval,就能做出簡單的專注/休息計時器。以下以「工作 25 分鐘、休息 5 分鐘」為例。

頁面結構

HTML 部分包含標題、工作時間輸入、休息時間輸入、canvas 顯示區,以及兩個按鈕:開始工作與開始休息。

<header>
  <h1>work-life balance timer</h1>
</header>
<input id="workIntervalInput" type="number" value="25" min="15" max="45" step="5">
<input id="restIntervalInput" type="number" value="5" min="3" max="10" step="1">
<canvas id="countdownCanvas" width="300" height="50"></canvas>
<button onclick="startWorkCountDown()">Work Hard</button>
<button onclick="startRestCountDown()">Take A Break</button>

核心邏輯

JavaScript 的重點是:將分鐘轉為秒、每秒更新一次 canvas 文字,時間到時清除計時器並提示。

var canvas = document.getElementById("countdownCanvas");
var context = canvas.getContext("2d");
var countDownSeconds = 60;
var handle = null;

function updateCanvas() {
  if (countDownSeconds < 0) {
    clearInterval(handle);
    alert("時間到!");
    return;
  }
  var min = Math.floor(countDownSeconds / 60);
  var sec = countDownSeconds % 60;
  context.clearRect(0, 0, canvas.width, canvas.height);
  context.fillText(min + " : " + sec, canvas.width / 2, canvas.height / 2);
  countDownSeconds--;
}

function startWorkCountDown() {
  countDownSeconds = document.getElementById("workIntervalInput").value * 60;
  handle = setInterval(updateCanvas, 1000);
}

可延伸方向

這個範例可以加入開始/暫停按鈕、進度條、音效提醒,或把工作與休息時間存進 localStorage,讓下次開啟時保留設定。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved