淘先锋技术网

首页 1 2 3 4 5 6 7

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属性用于指定旋转的原点。