你可以使用 JavaScript 的 'setInterval' 函数来实现随时间变换的效果。下面是一个例子:

// 获取显示时间的元素
var timeElement = document.getElementById('time');

// 设置每秒钟更新一次时间
setInterval(function() {
  var now = new Date();
  var hours = now.getHours();
  var minutes = now.getMinutes();
  var seconds = now.getSeconds();
  
  // 格式化时间,确保始终是两位数
  var formattedTime = (hours < 10 ? '0' + hours : hours) + ':' + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds);
  
  // 更新显示时间的元素
  timeElement.textContent = formattedTime;
}, 1000);

在上面的例子中,我们首先通过 'document.getElementById' 获取显示时间的元素,然后使用 'setInterval' 函数每秒钟更新一次时间。在更新时间的回调函数中,我们使用 'new Date()' 获取当前时间,并将小时、分钟和秒数格式化成两位数的字符串。最后,将格式化后的时间更新到显示时间的元素中。

你可以将上述代码添加到你的 HTML 文件中,并将显示时间的元素的 ID 替换为你实际使用的元素 ID。


原文地址: https://www.cveoy.top/t/topic/qhzB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录