CSS代码不多,这里没有引入CSS样式,css样式在style里写
div类名line代表表内的刻度线,center代表中间遮挡多余线的圆,second秒针,minute分针,hour时针,origin代表圆中心的点(只是装饰效果)
第一步要先让父盒子居中再把盒子变成一个圆给个边框,因为后面要把刻度线及表针定位到父盒子身上,采用子绝父相的定位方式,先给父盒子添加上相对定位position: relative;
<body>
<div class="box">
<div class="line"></div>
<div class="line"></div>
<div class="line"></div>
<div class="line"></div>
<div class="line"></div>
<div class="line"></div>
<div class="center"></div>
<div class="second"></div>
<div class="minute"></div>
<div class="hour"></div>
<div class="origin"></div>
</div>
</body>
.box {
width: 300px;
height: 300px;
border: 3px solid black;
border-radius: 50%;
margin: 100px auto;
position: relative;
}
第二步:圆里面的刻度其实是用六根线经过旋转变成的。把线的样式写完后定位到大圆里,我们之前已经给大圆加了相对定位所以这里我们只要给线绝对定位position: absolute;就可以定位到大圆里left:50%;大圆的一半就到了中间位置,再使用伪类选择器分别选中第2,3,4,5,6分别旋转30deg。
.line {
position: absolute;
left: 50%;
height: 300px;
width: 3px;
background-color: #ccc;
}
.box .line:nth-child(2){
transform: rotate(30deg);
}
.box .line:nth-child(3){
transform: rotate(60deg);
}
.box .line:nth-child(4){
transform: rotate(90deg);
}
.box .line:nth-child(5){
transform: rotate(120deg);
}
.box .line:nth-child(6){
transform: rotate(150deg);
}
第三步在大圆里再套一个圆,目的就是让中间部分的线隐藏掉只留下边缘的线。定位到大圆里top50%,left50%会偏右下,要居中再给一个平移自身高度和宽度的一半transform: translate(-50%,-50%);
.box .center {
position: absolute;
top: 50%;
left: 50%;
height: 200px;
width: 200px;
transform: translate(-50%,-50%);
background-color: #fff;
border-radius: 50%;
}
第四步就是写针了,先写秒针,我这里写了height:100px,width:2px; 高度根据自己需求可以调一调,使用动画animation: second 60s steps(60) infinite;还有几个属性这里就不多做介绍了
定义动画 @keyframes second second是动画名称(自己取的)要与使用动画的名字一样
60s就是转完一圈的时间
steps( )分步动画,效果就是让表针一帧一帧的跳
infinite 无限循环
要注意的是要设置旋转中心的原点不然就会按照自己的原点旋转transform-origin: center bottom;
.second {
position: absolute;
left: 50%;
bottom: 50%;
height: 100px;
width: 2px;
background-color: red;
animation: second 60s steps(60) infinite;
transform-origin: center bottom;
}
@keyframes second {
to {
transform: rotate(360deg);
}
}
分针,与秒针写法基本相同高度及宽度根据自己需求调一调,要把旋转一圈的时间改为3600s
.minute {
position: absolute;
left: 50%;
bottom: 50%;
height: 80px;
width: 4px;
background-color: black;
transform-origin: center bottom;
animation: minute 3600s steps(60) infinite;
}
@keyframes minute{
to {
transform: rotate(360deg);
}
}
时针,把旋转一圈的时间改为43200s
.hour {
position: absolute;
left: 50%;
bottom: 50%;
height: 60px;
width: 7px;
background-color: black;
transform-origin: center bottom;
animation: minute 43200s steps(60) infinite;
}
@keyframes hour{
to {
transform: rotate(360deg);
}
最后就是圆中心的一点装饰
.origin{
position: absolute;
top: 50%;
left: 50%;
width: 20px;
height: 20px;
transform: translate(-7px,-10px);
border-radius: 50%;
background-color: black;
}
到此就结束了,谢谢!