【发布时间】:2021-01-04 00:07:12
【问题描述】:
我的基本 HTML 如下:
<!DOCTYPE html>
<html>
<head>
<title>Art Maker!</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Monoton">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Pixel Art</h1>
<h2>Choose Grid Size</h2>
<form id="sizePicker">
Grid Height:
<input type="number" id="inputHeight" name="height" min="1" value="1">
Grid Width:
<input type="number" id="inputWidth" name="width" min="1" value="1">
<input type="submit">
</form>
<h2>Pick A Color</h2>
<input type="color" id="colorPicker">
<h2>Design Canvas</h2>
<table id="pixelCanvas"></table>
<script src="designs.js"></script>
</body>
</html>
以下 JavaScript 用于:
- 获取用户输入:高度和宽度
- 根据高度和宽度绘制网格
- 获取 HTML 颜色选择器
- 当用户单击单元格时,根据步骤 (3) 使用背景颜色填充单元格
我卡在第 (4) 步。我创建了一个函数 respondToClick(event) 并使用 eventListener 将它附加到 tblRow。 “单击”时应使用背景颜色填充单元格;但事实并非如此。请指教哪里出了问题。
//获取网格大小值;高度和宽度
let height = document.getElementById('inputHeight').value;
let width = document.getElementById('inputWidth').value;
const gridHeight = document.getElementById('inputHeight');
gridHeight.addEventListener("input", function() {
height = document.getElementById('inputHeight').value;
})
const gridWidth = document.getElementById('inputWidth');
gridWidth.addEventListener("input", function() {
width = document.getElementById('inputWidth').value;
})
/ 创建画布的函数
const table = document.getElementById('pixelCanvas');
function createCanvas(event) {
for (let h = 1; h <= height; h++) {
const row = document.createElement('tr');
for (let w = 1; w <= width; w++) {
const cell = document.createElement('td');
cell.style.cssText = "height: 15px; width: 15px";
row.appendChild(cell);
}
table.appendChild(row);
}
}
const form = document.querySelector('form');
// 将 createCanvas() 绑定到“提交”
form.addEventListener('submit', createCanvas);
// 更新颜色的事件监听器
let color = document.getElementById('colorPicker').value;
document.getElementById('colorPicker').onchange = function() {
color = this.value;
}
// 仅当用户点击时激活功能
function respondToClick(event) {
if (event.target.nodeName.toLowerCase() === 'td') {
event.target.style.backgroundColor = color;
}
}
const tblRow = document.getElementsByTagName('tr');
tblRow.forEach(row => function() {
row.addEventListener("click", respondToClick);
});
【问题讨论】:
-
控制台是否出现任何错误?
标签: javascript