HTML5是當前Web前端開發中不可或缺的技術,它的簡單易用性深受開發者的喜愛。通過HTML5,我們可以輕松地實現一些常見的網頁特效,如時鐘等。接下來,我們來看一下如何實現一個簡單的HTML5時鐘。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>HTML5時鐘</title> <style> #clock { width: 200px; height: 200px; border-radius: 50%; background-color: #fff; box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1); margin: 20px auto; position: relative; } #hour-hand, #minute-hand, #second-hand { position: absolute; left: 50%; top: 50%; border-top: 5px solid #000; border-radius: 5px; transform-origin: bottom center; transform: translate(-50%, -100%); } #hour-hand { height: 50px; width: 8px; } #minute-hand { height: 80px; width: 6px; } #second-hand { height: 90px; width: 4px; background-color: red; } #center-dot { position: absolute; height: 10px; width: 10px; border-radius: 50%; background-color: #000; left: 50%; top: 50%; transform: translate(-50%, -50%); } </style> </head> <body> <div id="clock"> <div id="hour-hand"></div> <div id="minute-hand"></div> <div id="second-hand"></div> <div id="center-dot"></div> </div> <script> function setClock() { const now = new Date(); const hour = now.getHours(); const minute = now.getMinutes(); const second = now.getSeconds(); const hourAngle = (hour % 12) * 30 + (minute / 60) * 30; 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(setClock, 1000); </script> </body> </html>
在上述HTML代碼中,我們定義了一個id為clock的div,它代表了整個時鐘。其中,三個用于指示時間的指針分別由id為hour-hand、minute-hand和second-hand的div表示。我們還通過CSS定義了它們的樣式。至于時鐘的表盤中心點,則由id為center-dot的div實現。
而JavaScript部分,我們采用setInterval方法每秒刷新一次時間,并根據時間計算出對應指針應該旋轉的角度,并將其應用到對應div上。