DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
網頁時鐘實作:登入時間、現在時間與停留秒數一次顯示
編輯:CSS詳解     

這段程式碼在右上角放一個大號時鐘,每 200 毫秒更新一次,並示範了如何處理舊瀏覽器的不同 DOM 寫法。

放入 <head> 的計時函式

<script language=JavaScript>
function clockon() {
  thistime = new Date()
  var hours   = thistime.getHours()
  var minutes = thistime.getMinutes()
  var seconds = thistime.getSeconds()

  // 補零:個位數前面加 0,讓 9 分顯示成 09
  if (eval(hours)   < 10) { hours   = "0" + hours }
  if (eval(minutes) < 10) { minutes = "0" + minutes }
  if (seconds < 10)      { seconds = "0" + seconds }

  thistime = hours + ":" + minutes + ":" + seconds

  if (document.all) {
    bgclocknoshade.innerHTML = thistime
    bgclockshade.innerHTML   = thistime
  }

  // Netscape 4 的寫法,用 document.layers 判斷
  if (document.layers) {
    document.bgclockshade.document.write(
      '<div id="bgclockshade" style="position:absolute;visibility:visible;' +
      'font-family:Verdana;color:#FFAAAA;font-size:120px;top:10px;left:152px">' +
      thistime + '</div>')
    document.bgclocknoshade.document.write(
      '<div id="bgclocknoshade" style="position:absolute;visibility:visible;' +
      'font-family:Verdana;color:#DDDDDD;font-size:120px;top:10px;left:150px">' +
      thistime + '</div>')
    document.close()
  }

  var timer = setTimeout("clockon()", 200)
}
</script>

頁面部分

<body onLoad="clockon()">

<div id="bgclockshade"
     style="position:absolute;visibility:visible;font-family:Arial;
            color:#FF8888;font-size:120px;top:102px;left:152px"></div>

<div id="bgclocknoshade"
     style="position:absolute;visibility:visible;font-family:Arial;
            color:#DDDDDD;font-size:120px;top:100px;left:150px"></div>

<div id="mainbody" style="position:absolute;visibility:visible"></div>

兩個巧思

用兩層文字做立體感。粉紅色的 bgclockshade 放在 top:102px、left:152px,淺灰的 bgclocknoshade 放在 top:100px、left:150px,兩者相差 2 像素,看起來就像淺色數字下方有一層陰影。這是不支援 text-shadow 的年代常用的土法煉鋼。

補零的字串處理。把數字轉成字串後,個位數前面補一個 "0"。注意原始碼在 hours 與 minutes 前面多寫了 eval(),那是多余的——此時它們已經是數字了。

現代重寫

function pad(n) { return String(n).padStart(2, "0"); }

const opened = Date.now();
const clock  = document.getElementById("clock");
const stay   = document.getElementById("stay");

function tick() {
  const now = new Date();
  clock.textContent =
    `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;

  const s = Math.floor((Date.now() - opened) / 1000);
  stay.textContent =
    `已停留 ${Math.floor(s / 60)} 分 ${pad(s % 60)} 秒`;

  setTimeout(tick, 1000);
}
tick();

用 padStart(2, "0") 一行取代三個 if,陰影則用 text-shadow: 2px 2px 0 #FF8888 一行取代兩個 div。若要顯示登入時間,在頁面載入時記下 Date.now() 即可,也就是範例裡的 opened。

最後,倒數或計時不要用「累加計數器」的方式:瀏覽器在背景分頁會把 setTimeout 降頻到至少每秒一次,累加就會落後。一律用「現在時間減去起始時間」重算,誤差才不會累積。另外別忘了把 setTimeout 改成 requestAnimationFrame 或至少在 visibilitychange 時暫停,可省下不少電力。

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