js实现时钟
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>Js版带表盘的时钟</title> 5 <meta charset="utf-8"/> 6 <link rel="Stylesheet" href="4_2.css"/> 7 <script src="4_2.js"></script> 8 </head> 9 <body> 10 <div id="clock"> 11 <div id="h"></div> 12 <div id="m"></div> 13 <div id="s"></div> 14 <div id="a1">I</div> 15 <div id="a2">II</div> 16 <div id="a3">III</div> 17 <div id="a4">IIII</div> 18 <div id="a5">V</div> 19 <div id="a6">VI</div> 20 <div id="a7">VII</div> 21 <div id="a8">VIII</div> 22 <div id="a9">IX</div> 23 <div id="a10">X</div> 24 <div id="a11">XI</div> 25 <div id="a12">XII</div> 26 </div> 27 </body> 28 </html>
1 #clock{width:100px; height:100px; 2 border-radius:50%; 3 border:2px solid black; 4 position:relative; 5 } 6 #s{width:2px; height:55px; 7 position:absolute; top:5px; left:49px; 8 background-color:red; 9 transform-origin:50% 45px; 10 } 11 #m{width:4px; height:50px; 12 position:absolute; top:10px; left:48px; 13 background-color:black; 14 transform-origin:50% 40px; 15 } 16 #h{width:6px; height:45px; 17 position:absolute; top:15px; left:47px; 18 background-color:black; 19 transform-origin:50% 35px; 20 } 21 div[id^="a"]{position:absolute; 22 font-size:.5em; text-align:center; 23 width:7px; height:5px; 24 top:0; left: 46.5px; 25 transform-origin:50% 50px; 26 } 27 #a4,#a8{font-size:.4em; font-weight:bold} 28 #a1{transform:rotate(30deg)} 29 #a2{transform:rotate(60deg)} 30 #a3{transform:rotate(90deg)} 31 #a4{transform:rotate(120deg)} 32 #a5{transform:rotate(150deg)} 33 #a6{transform:rotate(180deg)} 34 #a7{transform:rotate(210deg)} 35 #a8{transform:rotate(240deg)} 36 #a9{transform:rotate(270deg)} 37 #a10{transform:rotate(300deg)} 38 #a11{transform:rotate(330deg)}
js代码:
1 var clock={ 2 divH:null, 3 divM:null, 4 divS:null, 5 start:function(){ 6 var self=this; 7 self.divH=document.getElementById("h"); 8 self.divM=document.getElementById("m"); 9 self.divS=document.getElementById("s"); 10 self.calc(); 11 setInterval(function(){self.calc();},1000);//this.calc.bind(this); 12 }, 13 calc:function(){ 14 var now=new Date(); 15 var h=now.getHours(); 16 h>12&&(h-=12); 17 var m=now.getMinutes(); 18 var s=now.getSeconds(); 19 var sdeg=s*6; 20 var mdeg=m*((360-s/60)/60); 21 var hdeg=h*((360-mdeg/60)/12); 22 this.divH.style.transform="rotate("+hdeg+"deg)"; 23 this.divM.style.transform="rotate("+mdeg+"deg)"; 24 this.divS.style.transform="rotate("+sdeg+"deg)"; 25 } 26 } 27 window.onload=function(){ 28 clock.start(); 29 }
效果展示!