1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 使用JavaScript实现动态显示当前日期和时间

使用JavaScript实现动态显示当前日期和时间

时间:2018-12-07 02:25:21

相关推荐

使用JavaScript实现动态显示当前日期和时间

1、新建一个index.html并添加一个用于显示时间的标签

index.html

<!DOCTYPE html><html><head><title>使用JavaScript实现动态显示当前日期和时间</title></head><body>当前时间:<p id="datetime"></p></body></html>

2、在同一html文件中添加JavaScript代码实现时间更新

index.html

<script>//获取当前日期和时间function updateClock() {var now = new Date();var date = now.toLocaleDateString();var hours = now.getHours();var minutes = now.getMinutes();var seconds = now.getSeconds();hours = checkTime(hours);minutes = checkTime(minutes);seconds = checkTime(seconds);document.getElementById('datetime').innerHTML = date + "\t" + hours + ":" + minutes + ":" + seconds;}// 在数字前面补0function checkTime(i) {if (i < 10) {i = "0" + i} return i;}setInterval(updateClock, 1000); // 每秒更新一次</script>

完整代码

index.html

<!DOCTYPE html><html><head><title>使用JavaScript实现动态显示当前日期和时间</title></head><body>当前时间:<p id="datetime"></p><script>//获取当前日期和时间function updateClock() {var now = new Date();var date = now.toLocaleDateString();var hours = now.getHours();var minutes = now.getMinutes();var seconds = now.getSeconds();hours = checkTime(hours);minutes = checkTime(minutes);seconds = checkTime(seconds);document.getElementById('datetime').innerHTML = date + "\t" + hours + ":" + minutes + ":" + seconds;}// 在数字前面补0function checkTime(i) {if (i < 10) {i = "0" + i} return i;}setInterval(updateClock, 1000); // 每秒更新一次</script></body></html>

运行结果

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。