要实现一个时钟效果,直接上代码吧!使用的素材的网址是:
http://events.dianping.com/active/campus/clock1.png
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8" /> 5 <script> 6 window.οnlοad=function(){ 7 var hourEle=document.getElementById("hour"); 8 var minuteEle=document.getElementById("minute"); 9 var secondEle=document.getElementById("second"); 10 function Clock(hourEle,minuteEle,secondEle){ 11 this.hourHand=hourEle; 12 this.minuteHand=minuteEle; 13 this.secondHand=secondEle; 14 } 15 16 Clock.prototype={ 17 setTime:function(hour,minute,second){ 18 this.hourHand.style.webkitTransform="rotate("+hour*360/12+"deg)"; 19 this.minuteHand.style.webkitTransform="rotate("+minute*360/60+"deg)"; 20 this.secondHand.style.webkitTransform="rotate("+second*360/60+"deg)"; 21 }, 22 run:function(){ 23 var self=this; 24 setInterval(function(){ 25 var date=new Date(); 26 var hour=date.getHours(); 27 var minute=date.getMinutes(); 28 var second=date.getSeconds(); 29 self.setTime(hour,minute,second); 30 },1000); 31 } 32 }; 33 34 35 var clock=new Clock(hourEle,minuteEle,secondEle); 36 var date=new Date(); 37 var hour=date.getHours(); 38 var minute=date.getMinutes(); 39 var second=date.getSeconds(); 40 clock.setTime(hour,minute,second); 41 clock.run(); 42 } 43 </script> 44 <style> 45 .container{ 46 margin:auto; 47 position:absolute; 48 left:0px; 49 right:0px; 50 top:0px; 51 bottom:0px; 52 width:770px; 53 height:760px; 54 } 55 .clock{ 56 background-image:url("http://events.dianping.com/active/campus/clock1.png"); 57 background-position:-200px -60px; 58 width:770px; 59 height:760px; 60 } 61 .hour{ 62 background-image:url("http://events.dianping.com/active/campus/clock1.png"); 63 background-position:-120px -560px; 64 width:30px; 65 height:160px; 66 position:absolute; 67 left:363px; 68 top:230px; 69 -webkit-transform-origin:50% 90%; 70 } 71 .minute{ 72 background-image:url("http://events.dianping.com/active/campus/clock1.png"); 73 background-position:-75px -498px; 74 width:30px; 75 height:220px; 76 position:absolute; 77 left:366px; 78 top:170px; 79 -webkit-transform-origin:46% 94%; 80 } 81 .second{ 82 background-image:url("http://events.dianping.com/active/campus/clock1.png"); 83 background-position:-25px -465px; 84 width:30px; 85 height:315px; 86 position:absolute; 87 left:362px; 88 top:130px; 89 -webkit-transform-origin:56% 77%; 90 } 91 </style> 92 </head> 93 <body> 94 <div class="container"> 95 <div id="clock" class="clock"> 96 <div id="hour" class="hour"></div> 97 <div id="minute" class="minute"></div> 98 <div id="second" class="second"></div> 99 </div> 100 </div> 101 </body> 102 </html>
效果图如下: