闲来无事,用JS写了个时钟,只要思路理清了,做起来其实还挺简单的。
先发个效果链接 点击查看
Demo
代码实现
HTML
<div id="warp" >
<div id="clock" >
<div id="number">
<div><span>9</span></div>
<div><span>10</span></div>
<div><span>11</span></div>
<div><span>12</span></div>
<div><span>1</span></div>
<div><span>2</span></div>
<div><span>3</span></div>
<div><span>4</span></div>
<div><span>5</span></div>
<div><span>6</span></div>
<div><span>7</span></div>
<div><span>8</span></div>
</div>
<div id="houre" class="pointer" ></div>
<div id="minute" class="pointer" ></div>
<div id="second" class="pointer" ></div>
</div>
</div>
CSS
*{
padding:0;
margin:0;
}
html, body {
height: 100%;
background: #9c9;
}
#warp{
width:230px;
height:230px;
margin:50px auto;
}
#clock{
width:200px;
height:200px;
border-radius:115px;
border:15px solid #f96;
background:white;
position:relative;
}
#number div{
width:190px;
height:20px;
position:absolute;
left:10px;
top:90px;
}
#number span{
display:block;
width:20px;
height:20px;
}
.pointer{
position:absolute;
bottom:90px;
transform-origin:50% 90%;
-webkit-transform-origin:50% 90%;
}
#houre{
width:5px;
height:60px;
left:98px;
background:black;
}
#minute{
width:3px;
height:70px;
left:99px;
background:gray;
}
#second{
width:1px;
height:80px;
left:100px;
background:red;
}
这里要注意的是number里面div的宽度给够,要不然后面用JS布局会出现问题。
JavaScript
var oNumber=document.getElementById("number");
var oDiv=oNumber.getElementsByTagName("div");
var oSpan=oNumber.getElementsByTagName("span");
for(var i=0;i<oDiv.length;i++){
oDiv[i].style.WebkitTransform="rotate(" + i * 30 + "deg)";
}
for(var j=0;j<oSpan.length;j++){
oSpan[j].style.WebkitTransform="rotate("+ j * -30 + "deg)";
}
function ColorNumber(){
var oHoure=document.getElementById("houre");
var oMinute=document.getElementById("minute");
var oSecond=document.getElementById("second");
var nowTime=new Date();
var nowHoure=nowTime.getHours();
var nowMinute=nowTime.getMinutes();
var nowSecond=nowTime.getSeconds();
var houreDeg=(nowMinute/60)*30;
var minuteDeg=(nowSecond/60)*6;
oHoure.style.WebkitTransform="rotate("+ (nowHoure * 30+houreDeg) + "deg)";
oMinute.style.WebkitTransform="rotate("+ (nowMinute * 6+ minuteDeg) + "deg)";
oSecond.style.WebkitTransform="rotate("+ (nowSecond * 6) + "deg)";
}
ColorNumber();
setInterval(ColorNumber,1000);
这里主要代码就两段,一段是布局用的,让数字旋转到相应的位置并调整方向:
for(var i=0;i<oDiv.length;i++){
oDiv[i].style.WebkitTransform="rotate(" + i * 30 + "deg)";
}
for(var j=0;j<oSpan.length;j++){
oSpan[j].style.WebkitTransform="rotate("+ j * -30 + "deg)";
}
另一段是计算指针的角度,其中最重要的是在不满一小时或不满一分钟时,时针或分针应该转多少度:
var houreDeg=(nowMinute/60)*30;
var minuteDeg=(nowSecond/60)*6;
It's done.是不是很简单......
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。