利用CSS3新增的一些样式写了一个简陋的时钟,主要是transform、transition、transform-origin等属性的应用 ,还有transition的一些坑,之后在总结。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css" id="css">
*{
margin: 0;
padding: 0;
}
html,body{
height: 100%;
overflow: hidden;
}
#wrap{
width: 200px;
height: 200px;
border: 1px solid;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
border-radius: 50%;
}
#wrap > ul {
list-style: none;
}
ul > li{
position: absolute;
left:99px;
top: 0;
width: 2px;
height: 9px;
background: black;
transform-origin: center 100px;
}
ul > li:nth-child(5n+1){
height: 15px;
}
/*ul > li:nth-child(2){
transform: rotate(6deg);
}*/
#wrap > .hour{
position: absolute;
left: 97px;
top: 70px;
width: 6px;
height: 30px;
background: black;
transform-origin: center bottom;
}
#wrap > .min{
position: absolute;
left: 98px;
top:50px;
width: 4px;
height: 50px;
background: gray;
transform-origin: center bottom;
}
#wrap > .sec{
position: absolute;
left: 99px;
top: 30px;
width: 2px;
height: 70px;
background: red;
transform-origin: center bottom;
}
#wrap > .icon{
position: absolute;
left: 90px;
top: 90px;
width: 20px;
height: 20px;
background: pink;
border-radius: 50%;
}
</style>
</head>
<body>
<div id="wrap">
<ul>
</ul>
<div class="hour"></div>
<div class="min"></div>
<div class="sec"></div>
<div class="icon"></div>
</div>
</body>
<script type="text/javascript">
window.onload = function () {
var hourNode = document.querySelector("#wrap > .hour")
var minNode = document.querySelector("#wrap > .min")
var secNode = document.querySelector("#wrap > .sec")
var ulNode = document.querySelector("#wrap > ul")
var styleNode = document.createElement("style")
var liHtml = ""
var cssHtml=""
for(var i=0;i<60;i++){
liHtml += "<li></li>"
cssHtml += "ul > li:nth-child(" + (i+1) + "){transform: rotate(" + (i*6)+"deg);}"
if (i % 5 == 0){
}
}
ulNode.innerHTML = liHtml
styleNode.innerHTML += cssHtml
document.head.appendChild(styleNode)
move()
setInterval(move,1000)
function move () {
var date = new Date()
var s = date.getSeconds()
var m = date.getMinutes() + s/60
var h = date.getHours() + m/60
secNode.style.transform = "rotate("+(6*s) +"deg)"
minNode.style.transform = "rotate("+ (6*m)+"deg)"
hourNode.style.transform = "rotate("+(6*h) +"deg)"
}
}
</script>
</html>