今天参考网上的一些case学习了一下动态时钟的写法,先看看html和JS怎么写:
这里的函数还是比较简单的,主要是通过window.setInterval(changeClock, 1000);没秒调用一次changeClock,然后再通过innerHTML方法跟新页面显示。这里有一个问题,就是为什么月份要加1?
<script>
function changeClock()
{
var date = new Date();
this.month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1 ) : (date.getMonth() + 1 );
this.date = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
this.hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
this.minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
this.second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
document.getElementById("clock").innerHTML = date.getFullYear() + "-" + this.month + "-" + this.date + " " + this.hour + ":" + this.minute + ":" + this.second;
}
window.setInterval(changeClock, 1000);
</script>
html当然也很简单:
<html>
<head>
</head>
<body>
<div id="clock" style="float:right"></div>
</body>
</html>