CSS+JS实现一个时钟 发表于 2020-03-16 | 分类于 代码练习 效果如下:预览链接:(https://shanfeng606.github.io/practice_05/) 点击跳转 HTML代码1234567891011121314151617181920212223242526272829303132333435363738394041<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="style.css"></head><body> <div class="clock"> <div class="hour"> <div class="hr" id="hr"></div> </div> <div class="min"> <div class="mn" id="mn"></div> </div> <div class="sec"> <div class="sc" id="sc"></div> </div> </div> <script type='text/javascript'> const deg = 6; const hr = document.querySelector('#hr'); const mn = document.querySelector('#mn'); const sc = document.querySelector('#sc'); setInterval(() => { //定时器,以毫秒周期来调用函数 let day = new Date(); let hh = day.getHours() * 30; //一圈12h,每h旋转30度 let mm = day.getMinutes() * deg; let ss = day.getSeconds() * deg; hr.style.transform = `rotateZ(${(hh) + (mm / 12)}deg)`;//时针旋转角度还要加分针的旋转分量 mn.style.transform = `rotateZ(${mm}deg)`; sc.style.transform = `rotateZ(${ss}deg)`; }) </script></body></html> CSS代码123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990*{ margin: 0; padding: 0;}body{ display: flex; justify-content: center; align-items: center; /* vh? */ min-height: 100vh;/*相对于视口的高度。视口被均分为100单位的vh*/ background: #091921;}.clock{ width: 350px; height:350px; display: flex; justify-content: center;/*左右居中*/ align-items: center; /*上下居中*/ background: url(fb16d3ee670f310e93be4b7ad845ed8df32a405e.png); background-size:cover; /*覆盖整个尺寸*/ border:4px solid #091921; border-radius: 50%; /*box-shadow: h-shadow v-shadow blur spread color inset;右下正方向*/ box-shadow: 0 -15px 15px rgba(255,255,255,0.05), inset 0 -15px 15px rgba(255,255,255,0.05), 0 15px 15px rgba(0,0,0,0.3), inset 0 15px 15px rgba(0,0,0,0.3);}.clock:before{ content:''; position: absolute; width: 15px; height:15px; background:#fff; border-radius: 50%; z-index:1000;}.clock .hour,.clock .min,.clock .src{ position: absolute;}.clock .hour ,.hr{ width:160px; height:160px;}.clock .min ,.mn{ width:190px; height:190px;}.clock .sec ,.sc{ width:230px; height:230px;}.hr,.mn,.sc{ display: flex; justify-content: center; /* align-items: center; 避免指针居中对齐*/ position: absolute; border-radius:50%;}.hr:before{ content:''; position: absolute; width: 8px; height:80px; background:#ff105e; border-radius: 6px 6px 0 0; z-index:10;}.mn:before{ content:''; position: absolute; width: 4px; height:90px; background:#fff; border-radius: 6px 6px 0 0; z-index:11;}.sc:before{ content:''; position: absolute; width:2px; height:150px; background:#fff; border-radius: 6px 6px 0 0;/*左上 右上 右下 左下*/ z-index:12;}