html部分
<!-- 创建一个表盘和时分秒针还有毫秒 -->
<div class="witch">
<div class="hour"></div>
<div class="min"></div>
<div class="ms"></div>
<div class="s"></div>
</div>
css样式;(有些是设置js创建元素的样式)
* {
padding: 0;
margin: 0;
}
.witch {
position: relative;
width: 400px;
height: 400px;
/* box-sizing: border-box; */
border-radius: 50%;
border: 2px solid #f0f;
margin: 20px auto;
}
.witch p {
position: absolute;
top: 195px;
left: 198px;
width: 4px;
height: 10px;
background-color: #f0f;
text-align: center;
}
.witch p div {
font-size: 30px;
text-align: center;
}
.witch .scalems {
position: absolute;
top: 197px;
left: 199px;
width: 2px;
height: 6px;
background-color: #f0f;
}
.hour {
position: absolute;
top: 100px;
left: 192px;
width: 16px;
border-radius: 50% 50% 0 0;
height: 100px;
background-color: #f00;
transform-origin: bottom;
animation: ms calc(3600 * 12s) infinite;
z-index: 9;
}
.min {
position: absolute;
top: 80px;
left: 195px;
width: 10px;
border-radius: 50% 50% 0 0;
height: 120px;
background-color: #00f;
transform-origin: bottom;
animation: ms 3600s steps(60) infinite;
z-index: 90;
}
.ms {
position: absolute;
top: 50px;
left: 198px;
z-index: 99;
width: 4px;
border-radius: 50% 50% 0 0;
height: 150px;
background-color: #000;
transform-origin: bottom;
animation: ms 60s steps(60) infinite;
}
.s {
position: absolute;
top: 20px;
left: 198px;
z-index: 99;
width: 4px;
border-radius: 50% 50% 0 0;
height: 180px;
background-color: #0f0;
transform-origin: bottom;
animation: ms 1s steps(60) infinite;
}
/* 每个表针都是旋转360deg,只是时间不一样因此公用一个就行 */
@keyframes ms {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
核心代码js
var wicthEl = document.querySelector(".witch");
//先遍历出来小时刻度
for (var i = 1; i <= 12; i++) {
//创建刻度
var scale = document.createElement("p");
//顺便把数字也传进去
var rot = 30 * i;
var spanEl = document.createElement("div")
spanEl.innerText = i;
//已经在css设置样式全都定位在圆心,每一个翻转的角度不一样再向上移动的各自的位置;
scale.style.transform = "rotate(" + i * 30 + "deg) translateY(-195px)";
//两位数个一位数的宽度不一样;因此单独设置一下;
if (i >= 10) {
spanEl.style.transform = "rotate(" + i * -30 + "deg) translateX(-300%) translateY(0%)";
} else {
spanEl.style.transform = "rotate(" + i * -30 + "deg) translateX(-200%) translateY(0%)";
}
//把元素插入
scale.appendChild(spanEl)
wicthEl.appendChild(scale)
}
//同理插入分钟刻度
for (var i = 0; i < 60; i++) {
var scalems = document.createElement("p");
scalems.className = "scalems"
var rot = 30 * i;
scalems.style.transform = "rotate(" + i * 6 + "deg) translateY(-197px)";
wicthEl.appendChild(scalems)
}