css3实现钟表效果
利用css3 transform属性刻画钟表的的刻度以及指针的角度,代码如下:
<head>
<meta charset="UTF-8">
<title>Title</title>
<style id="style">
html{height:100%;}
body{width:100%;height:100%;margin:0;display:-moz-box;display:-webkit-box; display:box; -webkit-box-align: center; -moz-box-align: center; box-align:center; -webkit-box-pack:center;-moz-box-pack:center; box-pack:center; }
.clock{ width:200px;height:200px;border:4px solid black;border-radius:50%; position:relative; }
.clock ul{ width:100%; height:100%;position:relative;margin:0;padding:0; }
.clock ul li{list-style: none; position:absolute;top:0;left:99px;width:2px; height:5px; background:gray; transform-origin: center 100px; }
.clock ul li:nth-of-type(5n+1){ left:98px;width:4px;height:10px;background:black;}
.hour{ width:8px; height:60px; border-radius:4px; position:absolute;left:96px;top:40px; background-color:black;transform-origin: center 60px;box-shadow:0 0 10px rgba(0,0,0,0.8);} .min{width:6px;height:70px;border-radius:3px;position:absolute;left:97px;top:30px;background-color:#2b2b2b;transform-origin: center 70px;box-shadow:0 0 10px rgba(0,0,0,0.6);} .sec{width:4px;height:80px;border-radius:2px; position:absolute;left:98px;top:20px;background-color:red;transform-origin: center 80px;box-shadow:0 0 10px rgba(255,0,0,0.5);}
.center{width:16px;height:16px;box-shadow:0 2px 5px rgba(0,0,0,0.5); border-radius:50%;position:absolute;left:92px;top:92px;background-image: radial-gradient(white,gray);}
</style>
</head>
<body>
<div class="clock">
<ul id="tickBox">
</ul>
<div class="hour" id="hour"></div>
<div class="min" id="min"></div>
<div class="sec" id="sec"></div>
<div class="center"></div>
</div>
<script>
window.onload = function(){
var oUl = document.getElementById("tickBox");
var oStyle = document.getElementById("style");
var liStr = "";
var styleStr = "";
for(var i=0;i<60;i++){
styleStr += '.clock ul li:nth-of-type('+(i+1)+'){transform: rotate('+i*6+'deg);}';
liStr += '<li></li>';
}
oStyle.innerHTML += styleStr;
oUl.innerHTML = liStr;
var oHour = document.getElementById("hour");
var oMin = document.getElementById("min");
var oSec = document.getElementById("sec");
function getTime(){
var timer = new Date();
var sec = timer.getSeconds();
var min = timer.getMinutes();
var hour = timer.getHours();
var tranS = sec*360/60;
var tranM = (min+sec/60)*360/60;
var tranH = (hour + min/60)*360/12;
oSec.style.transform = 'rotate('+tranS+'deg) translateZ(-1px)';
oMin.style.transform = 'rotate('+tranM+'deg) translateZ(-1px)';
oHour.style.transform = 'rotate('+tranH+'deg) translateZ(-1px)';
}
setInterval(getTime,1000);
getTime();
}
</script>
</body>