我目前正在使用Javascript创建一个项目,旨在成为一种反应游戏"。按下"开始"按钮,根据一些辅助方法决定的颜色,大小,位置(边距)和形状(方框或圆形),屏幕上会弹出一个形状。目标是尽快点击形状,然后页面将打印所用的时间。然后会显示一个新形状并重复循环。
然而,一旦我按下"开始&#34>按钮,屏幕上没有任何内容。形状无处可见。
任何人都可以帮助让形状出现吗?我认为它与样式表有关,但我不太确定。
<html>
<head>
<title>Reaction Tester</title>
</head>
<body>
<h1>Test Your Reactions!</h1>
<p>Click on the boxes and circles as quickly as you can!</p>
<h2 id="recorded-time"></h2>
<button id="start-button">Begin!</button>
<div id="current-shape"></div>
<script type="text/javascript">
var beginTime = 0.0; //default value
document.getElementById("start-button").onclick = function() {
document.getElementById("start-button").style.display = "none";
newShape();
}
function decideShape() { //chooses between a circle or box(square)
var x = Math.random();
if(x < 0.5) {
return("circle");
} else {
return("box");
}
}
function decideColor() { //chooses between a list of 8 colors
var x = Math.random();
if(x < 0.125) {
return("red");
} else if(x < 0.25) {
return("blue");
} else if(x < 0.375) {
return("yellow");
} else if(x < 0.5) {
return("green");
} else if(x < 0.625) {
return("purple");
} else if(x < 0.75) {
return("black");
} else if(x < 0.875) {
return("gray");
} else {
return("#00FFFF"); //cyan
}
}
function decideSize() { //self explanatory
var value; //circle - radius, box - half of side length
value = Math.floor(Math.random() * 75) + 25; //diameter/side length set to be between 50 and 199
return value;
}
function decideMargin(size) { //depends on size of shape
var value;
value = Math.floor(Math.random()*(400 - size)) + size;
return value;
}
document.getElementById("current-shape").onclick = function() {
newShape();
}
function beginTimer() {
var bT = new Date();
beginTime = bT;
}
function stopTimer() {
var endTime = new Date();
var elapsedTime = endTime - beginTime;
document.getElementById("recorded-time").innerHTML = "Your time: " + (elapsedTime/1000.0) + " seconds";
}
function newShape() {
if(beginTime != 0.0) {
stopTimer();
}
var nextShape = decideShape();
var nextColor = decideColor();
var nextSize = decideSize();
var nextLeftMargin = decideMargin(nextSize);
var nextTopMargin = decideMargin(nextSize);
document.getElementById("current-shape").style.backgroundColor = nextColor;
document.getElementById("current-shape").style.marginLeft = nextLeftMargin;
document.getElementById("current-shape").style.marginTop = nextTopMargin;
if(nextShape = "circle") {
document.getElementById("current-shape").style.borderRadius = 50;
} else { //nextShape = "box"
document.getElementById("current-shape").style.borderRadius = 0;
}
beginTimer();
}
</script>
</body>
</html>
答案 0 :(得分:2)
您需要为“current-shape”div添加宽度和高度。
<div id="current-shape" style="width:100px;height:100px"></div>
你还需要在函数newShape中为nextShape和nextColor添加引号:
var nextShape = "circle";
var nextColor = "red";