js实现显示系统时间的表盘
核心:
1,document.styleSheets 修改css里的keyframes属性值
2,表针角度的计算
最终显示效果:
<!DOCTYPE html>
<html>
<head>
<title>实现表盘样式的时间显示</title>
<meta charset="utf-8"/>
<style>
div[id^="a"]{position:absolute;
font-size:.1em; text-align:center;
width:7px; height:5px;
top:0; left: 46.5px;
transform-origin:50% 50px;
}
#a1{transform:rotate(30deg)}
#a2{transform:rotate(60deg)}
#a3{transform:rotate(90deg)}
#a4{transform:rotate(120deg)}
#a5{transform:rotate(150deg)}
#a6{transform:rotate(180deg)}
#a7{transform:rotate(210deg)}
#a8{transform:rotate(240deg)}
#a9{transform:rotate(270deg)}
#a10{transform:rotate(300deg)}
#a11{transform:rotate(330deg)}
</style>
<style>
#clock{width:100px; height:100px;
border-radius:50%;
border:4px solid black;
position:relative;
}
#s{width:2px; height:55px;
position:absolute; top:5px; left:49px;
background-color:red;
transform-origin:50% 45px;
-webkit-animation:rotateS 60s linear infinite;
}
#m{width:4px; height:50px;
position:absolute; top:10px; left:48px;
background-color:black;
transform-origin:50% 40px;
-webkit-animation:rotateM 3600s linear infinite;
}
#h{width:6px; height:45px;
position:absolute; top:15px; left:47px;
background-color:black;
transform-origin:50% 35px;
-webkit-animation:rotateH 43200s linear infinite;
}
@-webkit-keyframes rotateS{
0%{transform:rotate(0deg)}
100%{transform:rotate(360deg)}
}
@-webkit-keyframes rotateM{
0%{transform:rotate(0deg)}
100%{transform:rotate(360deg)}
}
@-webkit-keyframes rotateH{
0%{transform:rotate(0deg)}
100%{transform:rotate(360deg)}
}
</style>
</head>
<body>
<div id="clock">
<div id="h"></div>
<div id="m"></div>
<div id="s"></div>
<div id="a1">I</div>
<div id="a2">II</div>
<div id="a3">III</div>
<div id="a4">IIII</div>
<div id="a5">V</div>
<div id="a6">VI</div>
<div id="a7">VII</div>
<div id="a8">VIII</div>
<div id="a9">IX</div>
<div id="a10">X</div>
<div id="a11">XI</div>
<div id="a12">XII</div>
</div>
<script>
window.onload=function(){
//获得当前页面第二个样式表文件
var sheet=document.styleSheets[1];
//获得sheet中三个keyframes
var Skeyframes=sheet.cssRules[4];
var Mkeyframes=sheet.cssRules[5];
var Hkeyframes=sheet.cssRules[6];
//获得三个keyframes下的内嵌rule
var SStartRule=Skeyframes.cssRules[0];
var SEndRule=Skeyframes.cssRules[1];
var MStartRule=Mkeyframes.cssRules[0];
var MEndRule=Mkeyframes.cssRules[1];
var HStartRule=Hkeyframes.cssRules[0];
var HEndRule=Hkeyframes.cssRules[1];
//计算当前时间对应的三个指针的角度
var now=new Date();
var h=now.getHours();
var m=now.getMinutes();
var s=now.getSeconds();
var hDeg=(h*3600+m*60+s)/(3600*12)*360;
var mDeg=(m*60+s)/3600*360;
var sDeg=360*s/60;
//设置三个指针起始角度分别为sDeg,mDeg,hDeg
SStartRule.style.transform=
"rotate("+sDeg+"deg)";
MStartRule.style.transform=
"rotate("+mDeg+"deg)";
HStartRule.style.transform=
"rotate("+hDeg+"deg)";
//设置三个指针的结束较为分别为其起始角度+360度
SEndRule.style.transform=
"rotate("+(sDeg+360)+"deg)";
MEndRule.style.transform=
"rotate("+(mDeg+360)+"deg)";
HEndRule.style.transform=
"rotate("+(hDeg+360)+"deg)";
}
</script>
</body>
</html>