用js实现一个实时电子时钟,网上找了几个背景图,效果图如下:
结构代码如下:
<div id="clock">
<div id="h"></div>
<div id="m"></div>
<div id="s"></div>
</div>
使用的背景图放在文章下方,css样式代码:
/* 背景表盘 */
#clock{
width: 600px;
height: 600px;
background: url('./images/clock.jpg') no-repeat center;
background-size: 100%;
position: relative;
/* 让时钟出现在网页中间区域 个人觉得看起来舒服点 */
left: 300px;
top: 20px;
}
/* 设置时针分针秒针背景图的大小位置以及旋转中心 */
#clock div{
width: 100%;
height: 100%;
position: absolute;
left: 285px;
top: 0;
transform-origin:15px 300px;
}
/* 分别添加时针分针秒针的背景图 */
#h{
background: url('./images/h.png') no-repeat;
}
#m{
background: url('./images/m.png') no-repeat;
}
#s{
background: url('./images/s.png') no-repeat;
}
最后是js代码:
<script>
//分别获取时针分针秒针的div
var hour=document.getElementById("h"),
minute=document.getElementById("m"),
second=document.getElementById("s");
//设置计时器16ms执行一次刷新获取时间,如果想要秒针缓慢跳动,可以设置500ms或者1000ms执行一次
setInterval(function(){
// 动态获取每个时间点
var date=new Date(),ms,s,m,h;
ms=date.getMilliseconds();
s=date.getSeconds()+ms/1000;
m=date.getMinutes()+s/60;
h=date.getHours()%12+m/60;
//计算该时间点每个指针分别转动的弧度
second.style.transform = "rotate("+ s*6 +"deg)";
minute.style.transform = "rotate("+ m*6 +"deg)";
hour.style.transform = "rotate("+ h*30 +"deg)";
},16)
</script>
附上本次使用的系列背景图,也可以自己选择不同的图来更换