我目前正在使用Javascript进行初学者课程,并且正在从事基本上是反应计时器的非常基本的项目。这个想法是随机的形状(只有正方形或圆形)随机出现在随机位置,用户必须点击它们。使用Javascript计算2个事件之间的时间
这是我到目前为止有:
document.addEventListener("DOMContentLoaded", function() {
var shape = document.getElementById("shape");
function generateRandomShape() {
console.log("TEST");
var shapeType = ["50%", ""];
var shapeColor = ["red", "green", "yellow", "purple", "orange", "brown", "gray", "black", "blue"];
shape.classList.remove("disappear");
shape.style.backgroundColor = shapeColor[Math.floor(Math.random() * shapeColor.length)];
shape.style.height = Math.random() * 300 + "px";
shape.style.width = shape.style.height;
shape.style.borderRadius = shapeType[Math.floor(Math.random() * shapeType.length)];
shape.style.marginLeft = Math.random() * 700;
shape.style.marginTop = Math.random() * 300;
}
shape.onclick = function() {
var endTime = Date.now();
var randomDelay = Math.random() * 3000;
var startTime = endTime - randomDelay;
var reaction = (endTime - startTime)/1000;
setTimeout(generateRandomShape, randomDelay);
shape.className = "disappear";
document.getElementById("end").innerHTML = endTime;
document.getElementById("start").innerHTML = startTime;
document.getElementById("reactionTime").innerHTML = reaction;
}
generateRandomShape();
});
.disappear {
display: none;
}
<h1>Test Your Reactions!</h1>
<p>Click on the boxes and circles as quickly as you can!</p>
<p>Your time is: <span id="reactionTime"></span> seconds</p>
<div id="shape"></div>
<div id="start"></div>
<div id="end"></div>
<div id="reactionTime"></div>
它所有的工作除了反应计时器确定,我只是不能工作如何得到这个工作。我在单击形状时创建了endTime变量,但无法使我的头部围绕startTime变量。如何存储形状出现的时间?显然,我在这里的尝试行不通,我可以很容易地看到为什么,但我无法弄清楚我应该放什么。任何帮助非常感谢!