可以使用JavaScript的`Date()`对象来获取当前时间,并使用`setInterval()`函数实现实时更新。
以下是一个示例代码:
<p id="time"></p>
function updateTime() {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var timeString = hours.toString().padStart(2, '0') + ":" +
minutes.toString().padStart(2, '0') + ":" +
seconds.toString().padStart(2, '0');
document.getElementById("time").innerHTML = timeString;
}
// 每秒钟更新一次时间
setInterval(updateTime, 1000);
?
这段代码会将当前时间格式化为 `xx:xx:xx` 的形式,并将其显示在id为 `time` 的元素中。同时,每秒钟会调用 `updateTime` 函数来更新时间。