js获取当前时间 一直加载
时间: 2023-08-24 14:07:08 浏览: 56
你可以使用JavaScript的Date对象来获取当前时间。以下是获取当前时间并实时更新的示例代码:
```javascript
function getCurrentTime() {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
// 格式化时间,保证显示两位数,不足补0
var timeString = formatTime(hours) + ":" + formatTime(minutes) + ":" + formatTime(seconds);
// 更新页面上显示的时间
document.getElementById("currentTime").textContent = timeString;
// 每秒钟调用一次getCurrentTime函数,实现实时更新
setTimeout(getCurrentTime, 1000);
}
function formatTime(time) {
return time < 10 ? "0" + time : time;
}
// 在页面加载完成后调用getCurrentTime函数
window.onload = function() {
getCurrentTime();
};
```
在上面的代码中,我们定义了一个`getCurrentTime`函数,它使用`Date`对象获取当前时间的小时、分钟和秒数,并格式化为字符串。然后,我们通过`document.getElementById`获取页面上的某个元素(例如一个`<span>`标签)来显示当前时间,这个元素的id属性为"currentTime"。我们使用`setTimeout`函数每隔一秒钟调用一次`getCurrentTime`函数,以实现实时更新。
你可以在页面上添加一个用于显示当前时间的元素,例如:
```html
<span id="currentTime"></span>
```
当页面加载完成后,调用`window.onload`事件处理函数来启动获取当前时间的过程。这样,页面上的当前时间将会一直更新。