js+css3 时钟
利用了css3里的transform:rotate(XXdeg)来写的一个时钟,在非IE浏览器下运行。
HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <style type="text/css"> #clock { list-style:none; padding:0; margin:100px auto; width:600px; height:600px; background:url(clockface.jpg) no-repeat 0 0; position:relative;} #clock li {height:600px; width:30px; position:absolute; top:0; left:50%; margin-left:-15px;} #hour { background:url(hourhand.png) no-repeat 0 0; } #minutes { background:url(minhand.png) no-repeat 0 0;} #seconds { background:url(sechand.png) no-repeat 0 0;} </style> </head> <body> <ul id="clock"> <li id="hour"></li> <li id="minutes"></li> <li id="seconds"></li> </ul> <script type="text/javascript" src="clock.js"></script> </body> </html>
JS:
function clock(){this.init.apply(this,arguments)}; clock.prototype = { init:function(opts){ opts = opts ||{}; var hour = this.getId(opts.hours || 'hour'); var minutes = this.getId(opts.minutes || 'minutes'); var seconds = this.getId(opts.seconds || 'seconds'); var time,nHour,nMinutes,nSeconds,srotate,mrotate,hrotate,sdegree,mdegree,hdegree; setInterval(function(){ time = new Date(); nHour = time.getHours(); nMinutes = time.getMinutes(); nSeconds = time.getSeconds(); //每格表示的度数为360/60=6度 sdegree = nSeconds * 6; mdegree = nMinutes * 6; //时针的度数应该为当前时间的小时数+与分针对应的小时度数 //(nHour%12) * 30 == (nHour%12) * (360/12) //nMinutes/2 == (nMinutes/60)*5*6 这里的(nMinutes/60)*5表示的是与分针对应的小时刻度,然后每格的度数6 hdegree = (nHour%12) * 30 + Math.floor(nMinutes/2); srotate = 'rotate(' + sdegree + 'deg)'; mrotate = 'rotate(' + mdegree + 'deg)'; hrotate = 'rotate(' + hdegree + 'deg)'; seconds.style.cssText = '-moz-transform:'+ srotate + '; -webkit-transform:' + srotate; minutes.style.cssText = '-moz-transform:'+ mrotate + '; -webkit-transform:' + mrotate; hour.style.cssText = '-moz-transform:'+ hrotate + '; -webkit-transform:' + hrotate; document.title = nHour + ':' + nMinutes + ':' + nSeconds; },1000); }, getId:function(el){ return typeof el=='string' ? document.getElementById(el) : el; } } new clock();
图片: