JS进阶级案例-----时钟
首先呢,是由四张图片构成,使用css摆放好,再使用JS给三个指针绑定获取时间和要旋转的角度,在获取对应的指针元素,给到定时器,实现时钟动态更新。
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>div{position: relative;}.cl{z-index: 1;}.hour{z-index: 2;margin-left: -320px;}.min{z-index: 3;margin-left: -35px;}.ss{z-index: 4;margin-left: -30px;}</style>
</head>
<body><div><img src="D:\VS web\JS\浏览器\时钟\clock.jpg" alt="" class="cl"><img src="D:\VS web\JS\浏览器\时钟\hour.png" alt="" class="hour"><img src="D:\VS web\JS\浏览器\时钟\minute.png" alt="" class="min"><img src="D:\VS web\JS\浏览器\时钟\second.png" alt="" class="ss"></div><script>function updateClock() {const now = new Date();const hour = now.getHours() % 12;const minute = now.getMinutes();const second = now.getSeconds();const hourDegree = ((hour + minute / 60 + second / 3600) * 30);const minuteDegree = ((minute + second / 60) * 6);const secondDegree = (second * 6);const hourHand = document.querySelector('.hour');const minuteHand = document.querySelector('.min');const secondHand = document.querySelector('.ss');hourHand.style.transform = `rotate(${hourDegree}deg)`;minuteHand.style.transform = `rotate(${minuteDegree}deg)`;secondHand.style.transform = `rotate(${secondDegree}deg)`;}updateClock();setInterval(updateClock, 1000);</script>
</body>
</html>
时钟
在我发布的视频里面也可以看效果
学到东西哦