在网页上实现时钟功能,效果如右图所示:
运用到的关键技术有:css3中的旋转、旋转基点设置
旋转:transform:rotate(*deg)
旋转基点:transform-origin: x轴偏移 y轴偏移
样式代码:
<style type="text/css" id="style"> #clock{ width:200px; height: 200px; border: 1px solid #000000; margin: 100px auto; border-radius: 50%; position: relative; } #ul{ margin: 0; padding: 0; list-style: none; position: relative; } #ul li{ width:2px; height: 6px; background:#000; position: absolute; top:0; left:98px; -webkit-transform-origin:center 100px; /*表盘上刻度的旋转中心点位于表盘中央,x轴中间,y轴距离顶部100的位置*/ } #ul li:nth-of-type(5n+1){height:10px; } #clock div{ position: absolute; -webkit-transform-origin:center bottom; } #hour{ width:8px; height:45px; background: #0c0c0c; left: 96px; top:55px; } #min{ width:6px; height:60px; background:#c0c0c0; left: 97px; top:40px; } #sec{ width:4px; height:80px; background: red; left: 98px; top:20px; } #ico{ width:20px; height: 20px; background: #000000; border-radius: 50%; left: 90px; top: 90px; } #time{ text-align: center; } </style>
javascript代码:
<script type="text/javascript"> window.onload = function(){ var oUl = document.getElementById(‘ul‘); var oHour = document.getElementById(‘hour‘); var oMin = document.getElementById(‘min‘); var oSec = document.getElementById(‘sec‘); var oStyle = document.getElementById(‘style‘); var oTime = document.getElementById(‘time‘); var iLi = ‘‘; var iStyle =‘‘; for(var i=0;i<60;i++) { iStyle+=‘#ul li:nth-of-type(‘+(i+1)+‘){-webkit-transform:rotate(‘+(i*6)+‘deg)}‘; iLi+=‘<li></li>‘; } oUl.innerHTML = iLi ; oStyle.innerHTML+=iStyle; function toMove(){ var iHour = ‘‘; var iMin = ‘‘; var iSec = ‘‘; var oDate = new Date(); iSec = oDate.getSeconds(); iMin = oDate.getMinutes()+iSec/60; iHour = oDate.getHours()+iMin/60; oSec.style.webkitTransform=‘rotate(‘+(iSec*6)+‘deg)‘; oMin.style.webkitTransform=‘rotate(‘+(iMin*6)+‘deg)‘;/**/ oHour.style.webkitTransform=‘rotate(‘+(iHour*30)+‘deg)‘;/*表盘12小时,共360度,每小时走30度*/ oTime.innerHTML=‘当前的时间是:‘+ Math.floor(iHour)+‘时‘+Math.floor(iMin)+‘分‘+iSec+‘秒‘; } setInterval(toMove,1000); }; </script>
网页布局代码:
<div id="clock"> <ul id="ul"> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> <div id="hour"></div> <div id="min"></div> <div id="sec"></div> <div id="ico"></div> </div> <div id="time"></div>
时间: 2024-10-12 16:22:44