JS实现时钟特效

时间:2021-03-17 08:54:45

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>JS实现时钟</title>
<style>
.clock {
width: 600px;
height: 600px;
margin:50px auto;
background: url(images/clock.jpg) no-repeat;
position: relative;
}
.clock div {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;

}
.h {
background: url(images/hour.png) no-repeat center center;
}
.m {
background: url(images/minute.png) no-repeat center center;
}
.s {
background: url(images/second.png) no-repeat center center;
}
</style>
</head>
<body>
<div class="clock" id="clock">
<div class="h" id="h"></div>
<div class="m" id="m"></div>
<div class="s" id="s"></div>
</div>
</body>
<script>
window.onload=function(){
function $(id){
return document.getElementById(id);
}
var clock=$('clock');
var hour=$('h');
var minute=$('m');
var second=$('s');
var s=0,m=0,h=0,ms=0;
function fn(){
var date=new Date();//得到最新的时间
ms=date.getMilliseconds();//得到毫秒数
// console.log(ms);
s=date.getSeconds()+ms/1000;//得到秒数 例如12.5S
m=date.getMinutes()+s/60;//得到分数 例如40.5M
h=date.getHours()%12+m/60;//得到小时 例如5.5H

//旋转角度
second.style.webkitTransform = 'rotate(' + s * 6 + 'deg)'; 
minute.style.webkitTransform = 'rotate(' + m * 6 + 'deg)'; 
hour.style.webkitTransform = 'rotate(' + h * 30 + 'deg)'; 
}
fn();
setInterval(fn,1000);
}
</script>
</html>

JS实现时钟特效