在HTML中,我们可以使用<time>
元素来表示时间及日期,其中可以使用时分秒来表示具体的时间,可以使用以下属性来设置时分秒:
<time datetime="2022-10-21T23:59:59">23:59:59</time>
上面的代码中,datetime
属性指定了时间的具体日期和时间,其格式为yyyy-MM-ddThh:mm:ss
。而时间本身则写在<time>
元素的内容中。
除了使用<time>
元素外,我们还可以使用JavaScript来动态设置时间。具体实现方法如下:
<p id="clock"></p> <script> function showTime() { var today = new Date(); var h = today.getHours(); var m = today.getMinutes(); var s = today.getSeconds(); h = checkTime(h); m = checkTime(m); s = checkTime(s); document.getElementById('clock').innerHTML = h + ":" + m + ":" + s; setTimeout(showTime, 1000); } function checkTime(i) { if (i < 10) {i = "0" + i}; // 添加前导0 return i; } showTime(); </script>
上面的代码中,我们使用setInterval()
函数来每隔1秒更新一次时间。其中checkTime()
函数用于添加前导0,确保小时、分钟、秒钟的显示格式统一。
上一篇 html时钟 指针为图片代码
下一篇 jquery 人脉关系图