3 回答
TA贡献1772条经验 获得超5个赞
Javascript代码
var timer = undefined;
function getShowTime() {
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
if (h == 0) {
}
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
return h + ":" + m + ":" + s;
}
function CurrentTime() {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
const time = getShowTime();
document.getElementById("txt").innerText = time;
}, 1000);
}
和 HTML 代码
<!DOCTYPE html>
<html dir="ltr">
<head>
<meta charset="utf-8">
<title>Digital Clock</title>
</head>
<body>
<input type="button" value="Start rit" onclick="CurrentTime()">
<div id="txt"></div>
<div id="Clock">
</div>
</body>
</html>
TA贡献1859条经验 获得超6个赞
如果您想每秒自动刷新一次,请使用:
<!DOCTYPE html>
<html dir="ltr">
<head>
<meta charset="utf-8">
<title>Digital Clock</title>
</head>
<body>
<input type="button" value="Start rit" onclick="ItsShowTime()">
<div id="txt"></div>
<div id="Clock">
<script type="text/javascript">
function ItsShowTime() {
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
if (h == 0) {}
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
var time = h + ":" + m + ":" + s;
setTimeout(ItsShowTime, 1000);
document.getElementById("txt").innerText = time;
}
</script>
</div>
</body>
</html>
如果不只是删除 setTimeout();
TA贡献1864条经验 获得超6个赞
如果你把它们分成两个单独的函数,这样会更容易:
var time;
function ItsShowTime(){
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
time = h + ":" + m + ":" + s;
document.getElementById("Clock").textContent = time;
setTimeout(ItsShowTime, 1000);
}
function CurrentTime(){
document.getElementById("txt").innerText = time;
}
ItsShowTime();
<!DOCTYPE html>
<html dir="ltr">
<head>
<meta charset="utf-8">
<title>Digital Clock</title>
</head>
<body>
<input type="button" value="Start rit" onclick="CurrentTime()">
<div id="txt"></div>
<div id="Clock">
</div>
</body>
</html>
添加回答
举报