我想将window.onblur
和window.onfocus
添加到现有的计数器脚本中。我想停止计时器onblur并再次启动计时器onfocus。
我不能让它工作,我不做怎么做。我尝试了各种可能性。但我是初学者。如果可以的话请帮忙。这是需要onblur和onfocus的工作代码:
$topbaroutput .= "
<script>
window.jQuery || document.write('<script src="jquery-2.2.4.min.js"><\/script>');
</script>
<table bgcolor="$bgcolor" border=0 cellpadding=0 cellspacing=0 width=40>
<tr><td align=center>
<div id="timer" style="font-size: 12pt; color: $fontColor; margin: 4px; "></div>
</td></tr>
</table>
<script language="javascript">
var timer=".$timer.";
function run () {
if (timer <= 0) {
document.getElementById("myform").style.visibility="visible";
document.getElementById("timer").innerHTML="GO";
} else {
document.getElementById("timer").innerHTML=timer;
timer--; setTimeout(run, 1000);
}
}
这是另一个有效的计数器代码,但我需要借助这些来制作另一个计数器脚本:
<!DOCTYPE html>
<html>
<body>
<div id="timer"></div>
<script>
var timer = 20;
var t;
var timer_is_on = 0;
function run() {
document.getElementById("timer").innerHTML=timer;
timer = timer - 1;
t = setTimeout(function(){ run() }, 1000);
}
window.onblur = function counterstops() {
clearTimeout(t);
timer_is_on = 0;
}
window.onfocus = function counterstarts() {
if (!timer_is_on) {
timer_is_on = 1;
run();
}
}
</script>
</body>
</html>
答案 0 :(得分:0)
<script language="text/javascript">
var SuperCoolTimerClass = function() {
// This was previously a string value but below you treat it
// as a numeric value. I changed this to be an arbitrary
// numeric value.
var timerCount = 100;
var timerTimeoutReference;
var timer_is_on = false;
this.run = function () {
if (timer <= 0) {
document.getElementById("myform").style.visibility="visible";
document.getElementById("timer").innerHTML="GO";
clearTimeout(timerTimeoutReference);
timer_is_on = false;
} else {
timer_is_on = true;
timerTimeoutReference = setTimeout(this.run, 1000);
document.getElementById("timer").innerHTML=timerCount;
timer--;
}
}
window.onblur = function counterstops() {
clearTimeout(timerTimeoutReference);
timer_is_on = false;
}
window.onfocus = function counterstarts() {
if (!timer_is_on) {
timer_is_on = true;
this.run();
}
}
}
var timerInstance = new SuperCoolTimerClass();
timerInstance.run();
</script>
您的代码示例中有一些内容: