根据Date()日期函数和Interval()定时器函数
实现代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</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();
// 在时、分、秒小于10时前面补0
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
var clockDisplay = hours + ":" + minutes + ":" + seconds;
document.getElementById("clock").innerHTML = clockDisplay;
}
// 每秒调用一次 updateClock 函数
setInterval(updateClock, 1000);
</script>
</body>
</html>
实现效果如下