JS实现简易刻度时钟示例代码
如图所示,利用JS实现简易的刻度时钟;
原理如下:利用60等份的li进行布局,li两两之间的间隔为6deg,把基点定在圆心上,使得li圆形分布。然后另外设置三条针线的样式的位置,基点同样定在圆心上,然后秒针每秒动6deg,分针每秒动1/60deg,时针每秒动1/3600deg。
布局代码如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css" id="sty"> *{ margin: 0; padding: 0; list-style: none; } #wrap{ width: 200px; height: 200px; border: 1px solid #000; border-radius: 50%; margin: 20px auto; position: relative; } #wrap ul{ position: relative; } #wrap ul li{ width: 2px; height: 6px; background: #000; position: absolute; left: 99px; top: 0; -moz-transform-origin: center 100px; } #wrap ul li:nth-child(5n){ height: 10px; } #con{ width: 10px; height: 10px; background: #000; border-radius: 50%; position: absolute; left: 95px; top: 95px; } #hour{ width: 5px; height: 70px; background: red; border-radius: 50%; position: absolute; left: 98px; top: 35px; -moz-transform-origin: center 65px; } #min{ width: 3px; height: 85px; background: #000; border-radius: 50%; position: absolute; left: 98.5px; top: 20px; -moz-transform-origin: center 80px; } #sec{ width: 2px; height: 100px; background: gray; border-radius: 50%; position: absolute; left: 98.5px; top: 20px; -moz-transform-origin: center 80px; } </style> </head> <body> <div id="wrap"> <ul id="list"> </ul> <div id="hour"></div> <div id="min"></div> <div id="sec"></div> <div id="con"></div> </div> </body> </html>
布局代码里需要注意的是:每隔四个刻度就有一个刻度比较长,所以我们在设置样式的时候要特别注意加上:#wrap ul li:nth-child(5n){height: 10px;}。第5n个的长度变长。
JS代码中主要搞清楚三针之间的度数关系就好做了,代码如下:
<script type="text/javascript"> window.onload=function(){ var oWrap=document.getElementById('wrap'); var oList=document.getElementById('list'); var oSty=document.getElementById('sty'); var tump=''; for(var i=0;i<60;i++){ var aLi=document.createElement('li'); oList.appendChild(aLi); tump+='#wrap ul li:nth-child('+(i+1)+'){transform: rotate('+(i+1)*6+'deg);}'; oSty.innerHTML+=tump; } var oSec=document.getElementById('sec'); var oMin=document.getElementById('min'); var oHour=document.getElementById('hour'); function time(){ var date=new Date(); var s=date.getSeconds(); var m=date.getMinutes()+(s/60); var h=date.getHours()+(m/60); oSec.style.transform='rotate('+s*6+'deg)'; oMin.style.transform='rotate('+m*6+'deg)'; oHour.style.transform='rotate('+h*30+'deg)'; } time(); setInterval(time,1000); } </script>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
JavaScript设计模式之原型模式(Object.create与prototype)介绍
这篇文章主要介绍了JavaScript设计模式之原型模式(Object.create与prototype)介绍,原型模式指使用原型实例来拷贝、创建新的可定制的对象,新建的对象,不需要知道原对象创建的具体过程,需要的朋友可以参考下2014-12-12javascript利用控件对windows的操作实现原理与应用
假如要发送汉字的聊天框的内容的话,我们也要从windows消息机制下手,先找到聊天消息的句柄(可以利用findwindow函数或者用spy工具哈),然后在找到上面的聊天框的句柄,接着我们就可以想这个句柄发送WM_SETTEXT的消息了2012-12-12
最新评论