html电子时钟模板代码

html电子时钟模板代码

html/div 2024-02-07 10:04:05 1年以前

HTML电子时钟是一种在网页中展示时间的实用工具。这里提供了一个简单的HTML电子时钟模板代码,可以根据需要进行修改。

<!DOCTYPE html>
<html>
<head>
<title>HTML电子时钟模板代码</title>
<style type="text/css">
#clock {
font-size: 30px;
font-weight: bold;
color: #333;
text-align: center;
}
</style>
</head>
<body onload="showClock()">
<div id="clock"></div>
<script type="text/javascript">
function showClock() {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
if(hours < 10) hours = "0" + hours;
if(minutes < 10) minutes = "0" + minutes;
if(seconds < 10) seconds = "0" + seconds;
document.getElementById("clock").innerHTML = hours + ":" + minutes + ":" + seconds;
setTimeout("showClock()", 1000);
}
</script> 
</body>
</html>

在这段代码中,我们首先定义了一个id为“clock”的div元素用于展示时钟。通过JavaScript中的Date对象获取当前的时间,然后将小时、分钟、秒钟数进行格式化,使其始终有两位数。最后通过innerHTML将时间展示到页面上。同时,我们使用了setTimeout函数来保证每秒钟更新一次时间。

文章版权声明:除非注明,否则均为网络转载文章,转载或复制请以超链接形式并注明出处。