Web - JavaScript实现页面实时显示时间
使用 setInterval() 函数
setInterval() 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式
setInterval("getTime()",1000);
以1000毫秒间隔调用函数有一个问题就是刚打开页面时的1s会不显示
为此我们可以在之前先调用一遍函数 getTime(),这样无论何时都能实时显示时间。
注意:<script>标签最好位于head里面(调用之前须先声明)
代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JS时间</title> <script> function getTime(){ var Week, Weekday; var date = new Date(); Week = ["星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]; Weekday = date.getDay(); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); hours = date.getHours(); minutes = date.getMinutes(); seconds = date.getSeconds(); document.getElementById("getTime").innerHTML = year + "年" + month + "月" + day + "日" + "\t" + hours + ":" + minutes + ":" + seconds + "\t" + Week[Weekday]; } </script> </head> <body> <div id="getTime" style="float: left; margin-left: 10px; margin-top: 15px; background-color: #aabbcc;"> <p> <script> getTime(); setInterval("getTime()",1000); </script> </p> </div> </body> </html>
效果展示: