用2d变换通过旋转、定位、动画整了个时钟:
html+css代码如下:
<!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>时钟</title>
<style>
* {
padding: 0;
margin: 0;
}
li {
list-style: none;
}
/* 表盘 */
.clock {
position: relative;
margin: 100px auto;
border-radius: 100px;
width: 200px;
height: 200px;
border: 2px solid black;
}
.clock::after {
content: '';
position: absolute;
top: 50%;
left: 50%;
margin-left: -90px;
margin-top: -90px;
width: 180px;
height: 180px;
border-radius: 90px;
background-color: #fff;
}
.clock ul li {
position: absolute;
left: 50%;
margin-left: -0.5px;
width: 1px;
height: 200px;
background-color: #000;
}
.clock ul li:nth-child(2) {
transform: rotate(30deg);
}
.clock ul li:nth-child(3) {
transform: rotate(60deg);
}
.clock ul li:nth-child(4) {
transform: rotate(90deg);
}
.clock ul li:nth-child(5) {
transform: rotate(120deg);
}
.clock ul li:nth-child(6) {
transform: rotate(150deg);
}
/* 指针 */
.h {
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -3px;
z-index: 2;
width: 6px;
height: 50px;
background-color: #000;
animation: h 86400s infinite;
transform-origin: bottom
}
.m {
position: absolute;
top: 50%;
left: 50%;
margin-top: -70px;
margin-left: -2px;
z-index: 2;
width: 4px;
height: 70px;
background-color: #000;
animation: h 3600s infinite linear;
transform-origin: bottom
}
.s {
position: absolute;
top: 50%;
left: 50%;
margin-top: -85px;
margin-left: -1px;
z-index: 2;
width: 2px;
height: 85px;
background-color: #000;
animation: h 60s infinite steps(60);
transform-origin: bottom
}
@keyframes h {
100% {
transform: rotate(360deg);
}
}
</style>
</head>
<body>
<div class="clock">
<!-- 表盘 -->
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<!-- 指针 -->
<div class="h" id="h"></div>
<div class="m" id="m"></div>
<div class="s"></div>
</body>
</html>
加点js让他动起来:
<script>
setInterval(() => {
var d = new Date();
// 获取小时
var h = d.getHours();
if (h >= 12)
{
h -= 12;
}
degh = h*30;
document.getElementById('h').style.transform = 'rotate(' + degh + 'deg)';
// 获取分钟
var m = d.getMinutes();
degm = m*6;
document.getElementById('m').style.transform = 'rotate(' + degm + 'deg)';
}, 100);
</script>
以上!