效果图
<!DOCTYPE html>
<html>
<head>
<meta charset="{CHARSET}" />
<title>js 获取以后工夫并实时刷新 </title>
<script>
// 页面加载调用
window.onload = function() {
// 每 1 秒刷新工夫
setInterval("NowTime()", 1000);
};
function NowTime() {
// 获取年月日
var time = new Date();
var year = time.getFullYear();
var month = time.getMonth();
var day = time.getDate();
// 获取时分秒
var h = time.getHours();
var m = time.getMinutes();
var s = time.getSeconds();
// 查看是否小于 10
h = check(h);
m = check(m);
s = check(s);
document.getElementById("nowtime").innerHTML =
"以后工夫:" +
year +
"年" +
month +
"月" +
day +
"日" +
h +
":" +
m +
":" +
s;
}
// 工夫数字小于 10,则在之前加个“0”补位。function check(i) {
// 办法一,用三元运算符
var num;
i < 10 ? (num = "0" + i) : (num = i);
return num;
// 办法二,if 语句判断
//if(i<10){
// i="0"+i;
//}
//return i;
}
</script>
</head>
<body>
<div id="nowtime"> 在这里显示工夫 </div>
</body>
</html>