我目前正在使用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變量。如何存儲形狀出現的時間?顯然,我在這裏的嘗試行不通,我可以很容易地看到爲什麼,但我無法弄清楚我應該放什麼。任何幫助非常感謝!