我正在使用PHP进行在线考试。
我希望倒数计时器在超时时自动触发提交按钮?
如果计时器达到1分钟标记,还可能在计时器下方显示另一个。
function startTimer(duration, display) {
var timer = duration,
minutes, seconds;
setInterval(function() {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function() {
var examTime = 60 * 5,
display = document.querySelector('#time');
startTimer(examTime, display);
};
#timediv {
background-color: #003300;
color: #ffffff;
font-size: 20px;
text-align: center;
}
<div id="timediv">Exam ends in <span id="time">05:00</span> minutes!</div>
<form action="samepage.php" method="post">
<input type="text" />
<input type="submit" value="Submit Answer Paper" />
</form>
在setInterval
回调中,检查时间是否已达到0:
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function() {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
if (minutes === 0 && seconds === 0) {
document.querySelector('form').submit()
}
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}'
您可以以相同的方式显示消息,但检查分钟数是否等于一。
if (minutes === 1 && seconds === 0) {
// Display an alert or another timer
}
您可以将此逻辑添加到startTimer
函数中:
// ...
if (--timer < 0) {
document.getElementById("theForm").submit();
// ...
}
// ...
您必须将id
上的<form>
属性设置为theForm
。