做法:最底层用div制作变盘,表盘数字使用transform: rotate();每小时数字乘以30度,进行位置摆放,使用定位将三个指针放到合适位置,使用transform-origin将旋转原点放到合适位置,最后使用setInterval,每秒获取时间,并将对应指针进行旋转。
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.dialPlate {
position: relative;
width: 200px;
height: 200px;
background-color: antiquewhite;
border-radius: 50%;
margin: 0 auto;
box-shadow: 0 0 8px #ccc;
}
.clockNum {
position: absolute;
top: 0;
left: 90px;
width: 20px;
height: 200px;
text-align: center;
padding-top: 4px;
font-weight: bold;
}
.innerDial {
position: absolute;
top: 50px;
left: 50px;
width: 100px;
height: 100px;
border-radius: 50%;
background-color: azure;
box-shadow: 0 0 8px #ccc;
}
.hourWheel {
position: absolute;
top: 60px;
left: 97px;
width: 6px;
height: 55px;
border-radius: 3px;
background-color: blueviolet;
transform-origin: 50% 40px;
transform: rotate(30deg);
box-shadow: 0 0 8px #ccc;
}
.minuteWheel {
position: absolute;
top: 40px;
left: 98px;
width: 4px;
height: 80px;
border-radius: 4px;
background-color: burlywood;
transform-origin: 50% 60px;
transform: rotate(45deg);
box-shadow: 0 0 8px #ccc;
}
.secondWheel {
position: absolute;
top: 30px;
left: 98.5px;
width: 3px;
height: 93px;
border-radius: 4px;
background-color: cadetblue;
transform-origin: 50% 70px;
box-shadow: 0 0 8px #ccc;
}
.innerCircle {
position: relative;
top: 91px;
left: 91px;
width: 18px;
height: 18px;
border-radius: 50%;
background-color: antiquewhite;
box-shadow: 0 0 8px #ccc;
}
</style>
</head>
<body>
<div class="dialPlate">
<div class="innerDial"></div>
<div class="hourWheel"></div>
<div class="minuteWheel"></div>
<div class="secondWheel"></div>
<div class="innerCircle"></div>
</div>
</body>
<script>
let dialPlate = document.querySelector('.dialPlate');
let hourWheel = document.querySelector('.hourWheel');
let minuteWheel = document.querySelector('.minuteWheel');
let secondWheel = document.querySelector('.secondWheel');
for (let i = 1; i < 13; i++) {
let clockNum = document.createElement('div');
clockNum.setAttribute('class', 'clockNum');
clockNum.innerText = i;
clockNum.style.setProperty('transform', `rotate(${i * 30}deg)`);
dialPlate.appendChild(clockNum);
};
setInterval(() => {
let date = new Date();
let h = date.getHours();
h = h > 12 ? h - 12 : h;
let m = date.getMinutes();
let s = date.getSeconds();
hourWheel.style.setProperty('transform',`rotate(${h * 30}deg)`);
minuteWheel.style.setProperty('transform',`rotate(${m * 6}deg)`);
secondWheel.style.setProperty('transform',`rotate(${s * 6}deg)`);
}, 1000);
</script>
</html>