我正在尝试制作一款测量你的反应时间的游戏,但我的最快得分跟踪器非常多。它在第一次反应测试期间有效但在此之后停止工作。提前感谢任何可以提供帮助的人。
<!DOCTPYE html>
<html>
<head>
<script>
window.onload = alert("Press START to start the game. As soon as the screen turns red click the stop button. Get the fastest time you can. Good luck");
var button = document.getElementById("reactionTester");
var start = document.getElementById("start");
var startTime;
var scoreContainer = document.getElementById("p");
var css = document.createElement("style");
css.type= "text/css";
var counter = 0;
var timer = null;
var highscore = document.getElementById("highscore");
var currentRecord = 0;
var highscoreCounter = 0;
function init(){
var startInterval/*in milliseconds*/ = Math.floor(Math.random()*10)*1000;
clearTimeout(timer);
timer = setTimeout(startTimer,1/*startInterval*/);
document.body.appendChild(css);
css.innerHTML = "html{background-color: blue;}";
}
function startTimer(){
startTime = Date.now();
css.innerHTML="null";
css.innerHTML = "html{background-color: red;}";
if(counter==1){
p1 = document.getElementsByTagName('p')[1];
p1.parentNode.removeChild(p1);
counter++;
}
}
function stopTimer(){
if(startTime){
var stopTime = Date.now();
var dif = stopTime - startTime;
alert("Your time is " + dif + " ms");
startTime = null;
css.innerHTML = null;
var p = document.createElement("p");
document.body.appendChild(p);
p.innerHTML = dif;
counter=1;
if (highscoreCounter != 0){
if(dif < currentRecord){
Phighscore2 = document.getElementsByTagName('p')[0];
Phighscore2.parentNode.removeChild(Phighscore2);
document.getElementById("highscore").appendChild(highscoreP);
currentRecord = dif;
highscoreP.innerHTML = currentRecord;
}
else{}
}
else{
var highscoreP = document.createElement("p");
document.getElementById("highscore").appendChild(highscoreP);
currentRecord = dif;
highscoreP.innerHTML = currentRecord;
highscoreCounter++;
}
}
else{
alert("don't trick me");
}
}
</script>
</head>
<body>
<div id="highscore">
</div>
<form id="form">
<div class="tableRow">
<input type="button" value="start" id="start" onclick="init()">
</div>
<div class="tableRow">
<input type="button" id="reactionTester" onclick="stopTimer()" value="stop">
</div>
<div id="p">
</div>
</form>
</body>
</html>
答案 0 :(得分:1)
您的问题是由highscoreP
本地定义变量function stopTimer
引起的。局部变量在函数返回时失去其值。使它成为一个全局变量(并且不要忘记在函数中删除它的'var'关键字。)
我无法拒绝对您的代码做一些额外的评论: