HTML(HyperText Markup Language)是一种用于创建网页的标准标记语言,而CSS(Cascading Style Sheets)则用于描述HTML文档的外观和布局。结合HTML和CSS,可以创建出各种静态或动态的网页元素,包括时钟。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Clock</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f0f0f0;
}
.clock {
width: 200px;
height: 200px;
border: 20px solid #333;
border-radius: 50%;
position: relative;
}
.hour, .minute, .second {
position: absolute;
left: 50%;
top: 50%;
transform-origin: bottom center;
}
.hour {
width: 6px;
height: 60px;
background-color: #333;
transform: translate(-50%, -100%) rotate(30deg);
}
.minute {
width: 4px;
height: 80px;
background-color: #666;
transform: translate(-50%, -100%) rotate(0deg);
}
.second {
width: 2px;
height: 90px;
background-color: #f00;
transform: translate(-50%, -100%) rotate(0deg);
}
</style>
</head>
<body>
<div class="clock">
<div class="hour"></div>
<div class="minute"></div>
<div class="second"></div>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic CSS Clock</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f0f0f0;
}
.clock {
width: 200px;
height: 200px;
border: 20px solid #333;
border-radius: 50%;
position: relative;
}
.hand {
position: absolute;
left: 50%;
bottom: 50%;
transform-origin: top center;
}
</style>
</head>
<body>
<div class="clock">
<div class="hand hour" id="hour"></div>
<div class="hand minute" id="minute"></div>
<div class="hand second" id="second"></div>
</div>
<script>
function updateClock() {
const now = new Date();
const hours = now.getHours() % 12 || 12;
const minutes = now.getMinutes();
const seconds = now.getSeconds();
const hourDeg = (hours * 30) + (minutes * 0.5);
const minuteDeg = minutes * 6;
const secondDeg = seconds * 6;
document.getElementById('hour').style.transform = `translate(-50%, 0) rotate(${hourDeg}deg)`;
document.getElementById('minute').style.transform = `translate(-50%, 0) rotate(${minuteDeg}deg)`;
document.getElementById('second').style.transform = `translate(-50%, 0) rotate(${secondDeg}deg)`;
setTimeout(updateClock, 1000);
}
updateClock();
</script>
</body>
</html>
setTimeout
或setInterval
正确设置,并且在页面加载后立即调用更新函数。通过以上示例代码和解释,你应该能够创建一个基本的HTML+CSS时钟,并了解其背后的基础概念和相关优势。
领取专属 10元无门槛券
手把手带您无忧上云