HTML畫時鐘是一項很有趣的技能,下面是一個簡單的時鐘代碼示例:
<html> <head> <title>HTML 時鐘</title> <style> .clock { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); border: 10px solid #333; border-radius: 50%; } .hour-hand { position: absolute; top: 50%; left: 50%; width: 40%; height: 6px; transform-origin: left; transform: translate(-20%, -50%) rotate(0deg); background-color: #fff; } .minute-hand { position: absolute; top: 50%; left: 50%; width: 60%; height: 4px; transform-origin: left; transform: translate(-30%, -50%) rotate(0deg); background-color: #fff; } .second-hand { position: absolute; top: 50%; left: 50%; width: 70%; height: 2px; transform-origin: left; transform: translate(-35%, -50%) rotate(0deg); background-color: #f00; z-index: 2; } </style> </head> <body> <div class="clock"> <div class="hour-hand"></div> <div class="minute-hand"></div> <div class="second-hand"></div> </div> <script> setInterval(function() { var d = new Date(); var h = d.getHours() % 12; var m = d.getMinutes(); var s = d.getSeconds(); var hourHand = document.querySelector(".hour-hand"); var minuteHand = document.querySelector(".minute-hand"); var secondHand = document.querySelector(".second-hand"); var hourAngle = h * 30 + m * 0.5; var minuteAngle = m * 6; var secondAngle = s * 6; hourHand.style.transform = "translate(-20%, -50%) rotate(" + hourAngle + "deg)"; minuteHand.style.transform = "translate(-30%, -50%) rotate(" + minuteAngle + "deg)"; secondHand.style.transform = "translate(-35%, -50%) rotate(" + secondAngle + "deg)"; }, 1000); </script> </body> </html>
該代碼包含HTML和JavaScript,通過設置定時器,每秒鐘更新表針的位置。其中,transform屬性用于旋轉和移動表針,transform-origin屬性用于指定旋轉的原點。