您好,我尝试使用HTML中的下拉列表悬停以使javascript表格单元格具有颜色,并可能更改表格单元格的像素大小。我只有HTML和javascript的非常基础的知识。
我尝试使用addEventListener函数,但是我不确定之后如何进行。
<html>
<head>
<script src="./javascript.js"></script>
<h1> Test A2 </h1>
</head>
<body>
<p>No. of Cols :
<input id="noOfCols" type="text" name="cols"/>
No. of Rows :
<input id="noOfRows" type="text" name="rows"/></p>
<p>Sample Cell Data :
<input id="scd" type="text" name="scdata"/>
Cell Height (in pixels) :
<input id="height" type="text" name="chip"/>
Cell Width (in pixels) :
<input id="width" type="text" name="cwip"/>
Cell Background Colour :
<select id="bgcolour" class="colour" name="cbc">
<option value="black">Black</option>
<option value="white">White</option>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="yellow">Yellow</option>
<option value="purple">Purple</option>
<option value="cyan">Cyan</option>
<option value="pink">Pink</option>
<option value="orange">Orange</option>
</select>
</p>
<button onClick="generate()">Generate Table</button>
<button onClick="deleteTable()">Clear Table</button><hr/>
<p id=generatedTable></p>
<hr/>
</body>
</html>
function generate()
{
var myTable = document.getElementById("generatedTable");
var table = document.createElement('TABLE');
table.border ='1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
var rows = document.getElementById("noOfRows");
var rowtext = Number(rows.value);
var cols = document.getElementById("noOfCols");
var coltext = Number(cols.value);
for (var y=0; y<rowtext; y++)
{
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var x=0; x<coltext; x++)
{
var td = document.createElement('TD');
td.width = 10;
td.height = 10;
td.align = "center";
var celltextInput = document.getElementById("scd");
var celltxt = celltextInput.value;
td.appendChild(document.createTextNode(celltxt));
var cellId = "cell [" + x + ", " + y + "]";
td.setAttribute("id", cellId.toString());
td.addEventListener("mouseover", function(){var bgcolour =
document.querySelector(".colour");
td.style.background = bgcolour.value;});
td.appendChild(document.createTextNode("Cell " + x + "," + y));
tr.appendChild(td);
}
}
myTable.appendChild(table);
}
function deleteTable()
{
var removeTable = document.getElementById("generatedTable");
removeTable.innerHTML = "";
}
function mouseOver(c) {
document.getElementById("bgcolour").style.color = c;
}
我希望表格单元格是彩色的,但是什么也没显示。非常感谢您的帮助,
答案 0 :(得分:1)
我尝试编辑此代码,现在可能是您期望的结果。 之后:
var td = document.createElement('TD');
添加:
td.addEventListener("mouseover", modifyColor, false);
在代码末尾,添加:
const modifyColor = event => {
const color = document.querySelector(".colour");
event.target.style.background = color.value;
}
答案 1 :(得分:0)
cellColor
cellColor = c;
td.style.backgroundColor = cellColor;
注意:此代码段存在严重问题:
td.addEventListener("mouseover", mouseOver());{
document.getElementById("generatedTable");}