查看效果:https:///keleyi/phtml/html5/17.htm
這個時鐘完全由 HTML、CSS 與 JavaScript 組成,不需要任何 GIF 或 Flash。指針是實體圖片,但旋轉角度由 CSS3 的 transform: rotate() 即時計算,日期數字則每秒更新一次。請使用支援 HTML5/CSS3 的瀏覽器查看。
時鐘本體是一張背景圖,三支指針則是三個絕對定位的 li,共用同一張指針圖但透過 background-position 對齊不同位置,並以 z-index 決定疊放次序:時針 1000、分針 2000、秒針 3000,秒針永遠在最上層。
#clock-keleyi-com {
position: relative;
width: 600px;
height: 600px;
list-style: none;
margin: 20px auto;
background: url('https:///image/a/nejs3bnm.png') no-repeat center;
}
#seconds, #minutes, #hours {
position: absolute;
width: 30px;
height: 580px;
left: 270px;
}
#date {
position: absolute;
top: 365px;
right: 140px;
color: #fff;
font: bold 30px/36px Acens;
letter-spacing: 3px;
text-shadow: 1px 2px 1px #000;
}
#hours { background: url('https:///image/a/exs0erm9.png') no-repeat left; z-index: 1000; }
#minutes { background: url('https:///image/a/exs0erm9.png') no-repeat center; width: 25px; z-index: 2000; }
#seconds { background: url('https:///image/a/exs0erm9.png') no-repeat right; z-index: 3000; }
$(document).ready(function () {
// 用陣列組出時鐘的 HTML,再以 join 串接,效能比連續字串相加好
var clock = [
'<ul id="clock-ke' + 'leyi-com">',
'<li id="date"></li>',
'<li id="seconds"></li>',
'<li id="hours"></li>',
'<li id="minutes"></li>',
'</ul>'
].join('');
$(clock).fadeIn().appendTo('body');
// 每秒自我呼叫一次,更新時鐘
(function Clock() {
var now = new Date();
var date = now.getDate();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
$("#date").html(date);
// 時針:一小時 30 度,再加上分針推進的零頭
var hrotate = hours * 30 + (minutes / 2);
$("#hours").css({
'transform': 'rotate(' + hrotate + 'deg)',
'-moz-transform': 'rotate(' + hrotate + 'deg)',
'-webkit-transform': 'rotate(' + hrotate + 'deg)'
});
// 分針與秒針:每格 6 度
var mrotate = minutes * 6;
$("#minutes").css({
'transform': 'rotate(' + mrotate + 'deg)',
'-moz-transform': 'rotate(' + mrotate + 'deg)',
'-webkit-transform': 'rotate(' + mrotate + 'deg)'
});
var srotate = seconds * 6;
$("#seconds").css({
'transform': 'rotate(' + srotate + 'deg)',
'-moz-transform': 'rotate(' + srotate + 'deg)',
'-webkit-transform': 'rotate(' + srotate + 'deg)'
});
setTimeout(Clock, 1000);
})();
});
時鐘指針的旋轉完全是角度問題。錶盤一圈 360 度、12 個小時刻度,所以每小時佔 30 度;分針與秒針一圈 60 格,所以每格 6 度。
值得注意的一行是 var hrotate = hours * 30 + (minutes / 2):加上 minutes / 2 這個零頭,是為了讓時針隨著分數連續前進,而不是每到整點才「跳」一格,這是很多新手版本會漏掉的細節。
另外,指針旋轉的起點必須是元素中心,實作上要確保指針圖片的旋轉軸落在錶盤中心;若圖片本身的長度或留白與預期不同,可以再用 transform-origin 微調。
範例中用到的 jQuery appendTo 與 css 方法,以及 box-shadow、-moz-box-shadow/-webkit-box-shadow 等前綴寫法,本站另有專文說明。若想要更平滑的秒針動效,可以在 transform 上加一條 transition: transform .2s,並把秒數換成含毫秒的計算方式。