所以我用javascript / jquery创建一个像素艺术品制作者,用户选择网格大小,并选择他们的颜色。通过表格中的tr元素,网格应该是完美的正方形。创建每个新行后,底部和顶部的行之间存在间隙,开发人员工具将显示添加的额外tr元素。
这是jsfiddle:https://jsfiddle.net/logikevcover/t9ezz3b9/
// Define the variables for the color picker id and size picker id
let colorPicker = document.getElementById('colorPicker');
let sizePicker = $('#sizePicker');
colorPicker.addEventListener("change", watchColorPicker, false);
function watchColorPicker(event) {
document.querySelectorAll('tr').forEach(function (tr){
tr.style.color = event.target.value;
});
}
// Size picker event handler which calls the makeGrid function
sizePicker.submit('click', function(){
event.preventDefault();
makeGrid();
});
// Sets the background color of the clicked td items to the color
selected
$('#pixel_canvas').on('click', 'td', function(){
$(this).css('backgroundColor', colorPicker.value);
});
// Creates the function to accept user input values to
// define the size of the grid
function makeGrid() {
let gridHeight = $('#input_height').val();
let gridWidth = $('#input_width').val();
let gridTable = $('#pixel_canvas');
let gridBody = '';
for (let i = 0; i < gridHeight; i++) {
gridBody += '<tr></tr>';
for (let j = 0; j < gridWidth; j++) {
gridBody += '<td></td>';
gridBody += gridWidth[i] + gridHeight[j];
}
}
gridTable.append(gridBody);
}
答案 0 :(得分:1)
原因是您在<tr>
变量中添加<td>
元素之前关闭了gridBody
元素。以下是解决这个问题的方法 -
for (let i = 0; i < gridHeight; i++) {
gridBody += '<tr>';
for (let j = 0; j < gridWidth; j++) {
gridBody += '<td></td>';
gridBody += gridWidth[i] + gridHeight[j];
}
gridBody += '</tr>';
}
在这里工作小提琴 - https://jsfiddle.net/t9ezz3b9/1/