CSS+JS实现一个时钟

效果如下:

预览链接:(https://shanfeng606.github.io/practice_05/) 点击跳转

HTML代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<!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代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
*{
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;
}
0%