<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>练习 - 网页时钟</title>
<style>
* {
box-sizing: border-box;
}
.clock {
width: 600px;
height: 600px;
background: url(./images/clock.jpg) no-repeat;
margin: 50px auto 0;
position: relative;
}
.hh,
.mm,
.ss {
position: absolute;
width: 100%;
height: 100%;
left: 0;
top: 0;
background: url(./images/hour.png) no-repeat center;
}
.mm {
background-image: url(./images/minute.png);
transform: rotate(270deg);
}
.ss {
background-image: url(./images/second.png);
transform: rotate(30deg);
}
</style>
</head>
<body>
<div class="clock">
<div class="hh" id="h"></div>
<div class="mm" id="m"></div>
<div class="ss" id="s"></div>
</div>
<script>
function clock() {
//get elements
const hh = document.querySelector('.hh')
const mm = document.querySelector('.mm')
const ss = document.querySelector('.ss')
//get time
const date = new Date()
const h = date.getHours()
const m = date.getMinutes()
const s = date.getSeconds()
//time turn css
// 小时角度公式:小时 * 30 + 分钟 / 60 * 30
// 分钟角度公式:分钟* 6 + 秒 / 60 * 6
// 秒角度公式: 当前秒数 * 6
hh.style.transform = `rotate(${h * 30 + m / 60 * 30}deg)`
mm.style.transform = `rotate(${m * 6 + s / 60 * 6}deg)`
ss.style.transform = `rotate(${s * 6}deg)`
}
clock()
setInterval(clock,1000)
</script>
</body>
</html>
素材: