我需要帮助以正确的结果制作正确的表格,而不是加一个
let table = document.getElementById("pixelCanvas");
let sizePicker = document.getElementById("sizePicker");
let height = document.getElementById("inputHeight").value;
let width = document.getElementById("inputWidth").value;
makeGrid(height, width);
sizePicker.addEventListener("click", (e) => {
e.preventDefault();
let height = document.getElementById("inputHeight").value;
let width = document.getElementById("inputWidth").value;
table.firstElementChild.remove();
makeGrid(height, width);
});
function makeGrid(height, width) {
for (let i = 0; i <= height; i++) {
let row = table.insertRow(i);
for (let j = 0; j <= width; j++) {
let cell = row.insertCell(j);
cell.addEventListener("click", (e) => {
cell.style.backgroundColor = color.value;
})
}
}
}
答案 0 :(得分:0)
我之所以这样做,只是因为它很有趣。
const in_H = document.querySelector('#input-Height')
, in_W = document.querySelector('#input-Width')
, btColor = document.querySelector('#Color-Button')
, btDraw = document.querySelector('#size-Picker')
, PixTab = document.querySelector('#pixel-Canvas')
;
function makeGrid()
{
let hMax = in_H.valueAsNumber
, wMax = in_W.valueAsNumber
;
PixTab.innerHTML = null
for (let h = 0; h < hMax; h++)
{
let row = PixTab.insertRow(h)
for (let w = 0; w < wMax; w++)
{ row.insertCell(w) }
}
}
makeGrid() // for init
btDraw.onclick = makeGrid
PixTab.onclick=e=>{
if (e.target.tagName.toLowerCase() != 'td') return
e.target.style.backgroundColor = btColor.value
}
table { border-collapse: collapse; margin: 1em }
td { border: 1px solid grey; width: 1em; height: 1em; }
<p>
height: <input type="number" min="5" max="20" value="5" id="input-Height">
width: <input type="number" min="5" max="20" value="5" id="input-Width" >
</p>
<p>
<input id="Color-Button" type="color" >
<button id="size-Picker" >draw new rect</button>
</p>
<table id="pixel-Canvas"></table>