以下是使用 JavaScript 制作一个简单钟表的示例代码:
<!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">
<style>
#clock {
width: 200px;
height: 200px;
border-radius: 50%;
background-color: #f0f0f0;
position: relative;
}
.hand {
width: 2px;
background-color: black;
position: absolute;
top: 50%;
left: 50%;
transform-origin: bottom center;
}
.hour-hand {
height: 80px;
}
.minute-hand {
height: 120px;
}
.second-hand {
height: 140px;
background-color: red;
}
</style>
</head>
<body>
<div id="clock">
<div class="hand hour-hand"></div>
<div class="hand minute-hand"></div>
<div class="hand second-hand"></div>
</div>
<script>
function updateClock() {
const now = new Date();
const hour = now.getHours() % 12;
const minute = now.getMinutes();
const second = now.getSeconds();
const hourAngle = (hour * 30) + (minute * 0.5);
const minuteAngle = (minute * 6);
const secondAngle = (second * 6);
const hourHand = document.querySelector('.hour-hand');
const minuteHand = document.querySelector('.minute-hand');
const secondHand = document.querySelector('.second-hand');
hourHand.style.transform = `rotate(${hourAngle}deg)`;
minuteHand.style.transform = `rotate(${minuteAngle}deg)`;
secondHand.style.transform = `rotate(${secondAngle}deg)`;
}
setInterval(updateClock, 1000);
updateClock();
</script>
</body>
</html>
这个示例中,首先通过 HTML 和 CSS 创建了钟表的基本结构和样式。然后,在 JavaScript 中,通过获取当前时间,计算时针、分针和秒针应该旋转的角度,并将其应用到相应的指针元素上,从而实现钟表的动态效果。
优势在于:
应用场景:
领取专属 10元无门槛券
手把手带您无忧上云