【发布时间】:2020-11-04 08:23:12
【问题描述】:
我是编码新手,已经解决了几天的问题,但没有找到解决方案。 我正在尝试使用由正方形组成的网格构建画布,当单击正方形时,它会更改其背景颜色。 我正在学习纯 javascript,我的问题是我找不到一种方法来引用单击的元素并仅更改其类,因为我的网格是由函数生成的。我这样做是因为我希望将来能够更改画布大小。 有关如何进行的任何建议?
HTML
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Square Canvas Game</title>
<link rel="stylesheet" href="style.css">
<link href="https://fonts.googleapis.com/css2?family=Merriweather:ital,wght@0,300;0,400;0,700;0,900;1,300;1,400;1,700;1,900&display=swap" rel="stylesheet">
</head>
<body onload="javascript:setInitialCanvas()">
<header>
<h1>Square artist</h1>
</header>
<div id="gameInterfaceContainer">
<button id="clearCanvas" onclick="clearAllSquares()">Clear All</button>
<div id="canvas">
</div>
</div>
<script src="script.js"></script>
</body>
</html>
JS
function setInitialCanvas(){
for (let i =0; i<400; i++){
let initialSquare = document.createElement("div");
document.getElementById("canvas").appendChild(initialSquare);
initialSquare.className = "canvasSquare clearSquare";
initialSquare.onclick = changeSquareColor(this);
initialSquare.style.backgroundColor = "white";
initialSquare.id = "square" + i;
}
}
function changeSquareColor(this){
let squareColor = ["white","blue","black","green","red","yellow","gray","brown"];
let colorIndex = 0;
while (squareColor[colorIndex] != this.style.backgroundColor){
colorIndex += 1;
}
if(this.style.backgroundColor == squareColor[squareColor.length]){
this.style.backgroundColor = squareColor[0];
}else
colorIndex += 1;
this.style.backgroundColor = squareColor[colorIndex];
}
谢谢!
*编辑:添加 codepen(不起作用)https://codepen.io/ccue92/pen/qBNKLQY
【问题讨论】:
-
你能在这里提供最小的可重现示例吗? codepen.io
-
codepen.io/ccue92/pen/qBNKLQY。现在它说“未捕获的 ReferenceError:setInitialCanvas 未在 onload (index.html:10) 处定义”并且无法理解为什么。我现在很迷茫
标签: javascript onclick this