以下是一个使用JavaScript创建简单电子时钟的示例:
一、基础概念
document.getElementById
等方法获取HTML元素,然后可以修改元素的属性(如innerHTML
)来更新时钟显示内容。setInterval
函数来按照一定的时间间隔(这里是每秒)执行更新时钟显示的操作。二、代码示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF - 8">
<meta name="viewport" content="width=device-width, initial - scale = 1.0">
<title>电子时钟</title>
<style>
#clock {
font - family: Arial, sans - serif;
font - size: 48px;
color: #333;
}
</style>
</head>
<body>
<div id="clock">00:00:00</div>
<script>
function updateClock() {
const now = new Date();
let hours = now.getHours();
let minutes = now.getMinutes();
let seconds = now.getSeconds();
hours = hours < 10? '0' + hours : hours;
minutes = minutes < 10? '0' + minutes : minutes;
seconds = seconds < 10? '0' + seconds : seconds;
const timeString = hours + ':' + minutes + ':' + seconds;
document.getElementById('clock').innerHTML = timeString;
}
setInterval(updateClock, 1000);
updateClock();//初始化时钟显示
</script>
</body>
</html>
三、优势
四、应用场景
领取专属 10元无门槛券
手把手带您无忧上云