此代碼創(chuàng)建了一個(gè)動態(tài)時(shí)鐘,其中 updateClock
函數(shù)會每秒更新一次當(dāng)前時(shí)間,并將其顯示在頁面上。JavaScript 的 setInterval
函數(shù)用于每秒調(diào)用 updateClock
函數(shù)以更新時(shí)鐘。以下是一個(gè)簡單的HTML和JavaScript代碼示例,用于在網(wǎng)頁上實(shí)現(xiàn)動態(tài)的時(shí)鐘:
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<meta name=“viewport” content=“width=device-width, initial-scale=1.0”>
<title>Dynamic Clock</title>
<style>
#clock {
font-family: Arial, sans-serif;
font-size: 48px;
font-weight: bold;
color: #333;
}
</style>
</head>
<body>
<div id=“clock”></div>
<script>
function updateClock() {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
// Add leading zeros if needed
hours = (hours < 10 ? “0” : “”) + hours;
minutes = (minutes < 10 ? “0” : “”) + minutes;
seconds = (seconds < 10 ? “0” : “”) + seconds;
// Format the time
var timeString = hours + “:” + minutes + “:” + seconds;
// Update the clock element
document.getElementById(“clock”).innerHTML = timeString;
}
// Update the clock every second
setInterval(updateClock, 1000);
// Initial call to display the clock immediately
updateClock();
</script>
</body>
</html>