原生js实现时钟

177 阅读1分钟

b.gif

css

   <style id="style">
       ul{
           list-style: none;
       }
       #circle{
           width: 200px;
           height: 200px;
           border-radius: 100px;
           border: 1px solid black;
       }
       #kedu li{
           width: 1px;
           height: 6px;
           border-radius: 10px;
           background-color: black;
           transform-origin: center 101px;
           position: absolute;
           left: 109px;
           top: 9px;
       }
       #kedu li:nth-of-type(5n+1){
           height: 12px;
           width: 2px;
       }
       #second{
           width: 2px;
           height: 80px;
           background-color: red;
           position: absolute;
           left: 108px;
           top: 30px;
           transform-origin: bottom;
       }
       #min{
           width: 2px;
           height: 65px;
           background-color: gray;
           position: absolute;
           left: 108px;
           top: 45px;
           transform-origin: bottom;
       }
       #hour{
           width: 2px;
           height: 50px;
           background-color: black;
           position: absolute;
          left: 108px;
           top: 60px;
           transform-origin: bottom;
       }
       #p12{
           position: absolute;
           left: 100px;
           top: 0px;
       }
       #p3{
           position: absolute;
           left: 190px;
           top: 84px;
       }
       #p6{
           position: absolute;
           left: 105px;
           top: 165px;
       }
       #p9{
           position: absolute;
           left: 20px;
           top: 82px;
       }
   </style>

html

<div id="circle">
    <ul id="kedu"></ul>
</div>
<div id="second"></div>
<div id="min"></div>
<div id="hour"></div>
<p id="p12">12</p>
<p id="p3">3</p>
<p id="p6">6</p>
<p id="p9">9</p>

js

<script>
    //绘制时钟的刻度 动态创建60个li标签。
    function li(){
        let ul=document.getElementById("kedu");
        let css;
        for(let i=0;i<60;i++){
            css+=`#kedu li:nth-of-type(${i+1}){transform:rotate(${i*6}deg)}`
            ul.innerHTML+=`<li></li>`;
        }
        let sty=document.getElementById("style")
        sty.innerHTML+=css
    }
    li();

    function time(){
        let s=document.getElementById("second");
        let m=document.getElementById("min");
        let h=document.getElementById("hour");

        //获取时间
        let date=new Date();
        let snum=date.getSeconds();
        let mnum=date.getMinutes()+snum/60;
        let hnum=date.getHours()+mnum/60;
        //分和秒是每次转6°,小时是30°
        s.style.transform=`rotate(${snum*6}deg)`;
        m.style.transform=`rotate(${mnum*6}deg)`
        h.style.transform=`rotate(${hnum*30}deg)`
    }
    setInterval(time,100)
</script>