原生 js 时钟实现

时间:2024-08-21 09:35:38
<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
padding: ;
margin: ;
box-sizing: border-box
} ul,
li {
list-style: none;
} .clock-box {
position: absolute;
width: 200px;
height: 200px;
top: %;
left: %;
margin-top: -100px;
margin-left: -100px;
} .clock-box:after {
content: '';
width: 10px;
height: 10px;
position: absolute;
top: %;
left: %;
margin-top: -5px;
margin-left: -5px;
background: rebeccapurple;
border-radius: 5px;
} .clock-box .tick-box {
position: relative;
width: %;
height: %;
border: 2px solid black;
border-radius: %;
} .clock-box .tick-box li {
position: absolute;
height: 2px;
width: 5px;
top: 97px;
left: -2px;
background-color: #;
transform-origin: 100px center;
} .clock-box .tick-box li:nth-child(5n+) {
width: 10px;
} .item {
position: absolute;
background-color: red;
transform-origin: center bottom;
} .seconds-hand {
height: 89px;
width: 1px;
top: 11px;
left: 99px;
transform: rotate(0deg)
} .minutes-hand {
height: 76px;
width: 2px;
top: 24px;
left: 98px;
transform: rotate(60deg);
background: green;
} .hours-hand {
height: 60px;
width: 4px;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
top: 40px;
left: 96px;
transform: rotate(72deg);
background: blue
}
</style>
</head> <body>
<div class="clock-box">
<ul class="tick-box">
</ul>
<div class="hours-hand item"></div>
<div class="minutes-hand item"></div>
<div class="seconds-hand item"></div>
</div>
</body>
<script>
const frag = document.createDocumentFragment();
const tickBox = document.querySelector('.tick-box')
const hour = document.querySelector('.hours-hand')
const minute = document.querySelector('.minutes-hand')
const second = document.querySelector('.seconds-hand')
for (let i = ; i < ; i++) {
let li = document.createElement('li');
li.style.transform = `rotate(${i * / }deg)`;
frag.appendChild(li)
}
tickBox.appendChild(frag) function time() {
const now = new Date();
const h = now.getHours();
const m = now.getMinutes();
const s = now.getSeconds();
hour.style.transform = `rotate(${(h+m/)*}deg)`
minute.style.transform = `rotate(${(m+s/)*}deg)`
second.style.transform = `rotate(${s*}deg)`
}
time()
setInterval(time, )
</script> </html>

效果如下:

原生 js 时钟实现