有什么方法可以让它运行秒表吗?我不需要任何开始或停止按钮,它应该只在页面加载时运行秒表并且秒表需要继续运行。
我已经让其他一切正常工作,但我找不到使用 00:00 格式作为秒表的函数。有什么命令可以做到这一点吗?
“d.getSeconds()”不是为我做的。
new Date();
var testVar = window.setInterval(update, 10);
function update() {
var d = new Date();
document.getElementById("seconds").innerHTML = d.getSeconds();
}
#seconds {
background-color: yellow;
max-width: 17%;
}
<!DOCTYPE html>
<head>
<title>
Stop Watch
</title>
</head>
<body>
<h1>
Stop Watch
</h1>
<p>Elapsed Time:</p>
<p id="seconds"></p>
</body>
有什么方法可以让 innerHTML 成为“00:00”格式的常规秒表吗?
最佳答案
按照您的操作方式,秒表可以从任意随机数开始(因为它从当前秒数开始)。我建议在下面简单地制作你自己的。 但是,如果您不想自己制作,请查看第二个或第三个片段。
var testVar = window.setInterval(update, 10);
var seconds = 0;
var milliseconds = 1;
function update() {
if (milliseconds == 100) {
milliseconds = 0;
seconds++;
}
if (milliseconds < 10 && seconds < 10) {
document.getElementById("seconds").innerHTML =
"0" + seconds + ":0" + milliseconds;
}
else if (milliseconds < 10 && seconds >= 10) {
document.getElementById("seconds").innerHTML =
seconds + ":0" + milliseconds;
}
else if (milliseconds >= 0 && seconds < 10) {
document.getElementById("seconds").innerHTML =
"0" + seconds + ":" + milliseconds;
}
else if (milliseconds >= 0 && seconds >= 10) {
document.getElementById("seconds").innerHTML =
seconds + ":" + milliseconds;
}
milliseconds++;
}
#seconds {
background-color: yellow;
max-width: 17%;
}
<!DOCTYPE html>
<head>
<title>
Stop Watch
</title>
</head>
<body>
<h1>
Stop Watch
</h1>
<p>Elapsed Time:</p>
<p id="seconds">00:00</p>
如果您想继续按照原来的方式进行操作,请查看下面的代码片段。我从 new Date()
得到了分和秒,并且基本上使用了一些你想要的 if 语句来格式化它。
update();
var testVar = window.setInterval(update, 10);
var seconds;
var milliseconds;
var d;
function update() {
d = new Date();
seconds = d.getSeconds();
milliseconds = Math.floor((d.getMilliseconds() / 10));
if (milliseconds < 10 && seconds < 10) {
document.getElementById("seconds").innerHTML =
"0" + seconds + ":0" + milliseconds;
}
else if (milliseconds < 10 && seconds >= 10) {
document.getElementById("seconds").innerHTML =
seconds + ":0" + milliseconds;
}
else if (milliseconds >= 0 && seconds < 10) {
document.getElementById("seconds").innerHTML =
"0" + seconds + ":" + milliseconds;
}
else if (milliseconds >= 0 && seconds >= 10) {
document.getElementById("seconds").innerHTML =
seconds + ":" + milliseconds;
}
}
#seconds {
background-color: yellow;
max-width: 17%;
}
<!DOCTYPE html>
<head>
<title>
Stop Watch
</title>
</head>
<body>
<h1>
Stop Watch
</h1>
<p>Elapsed Time:</p>
<p id="seconds"></p>
关于javascript - 如何使用 00 :00 time format?(秒:毫秒)修复我的 Javascript 秒表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54797380/