答案 0 :(得分:1)
这是可能性之一:
<table>
<tr>
<td>...</td>
<td>...</td>
</tr>
...
</table>
和JavaScript:
function toggleBG() {
if(this.className.indexOf("yellowBG") >= 0) {
var x = this.className;
this.className = x.split("yellowBG").join('');
} else {
this.className += "yellowBG";
}
}
var elem = document.getElementsByTagName('td');
for (var i = 0; i < elem.length; i++) {
elem[i].addEventListener('click', toggleBG,, false);
}
和CSS:
.yellowBG {
background: yellow;
}
答案 1 :(得分:0)
当用户点击单元格时,您只需要应用CSS类。您可以在第二次单击时删除该类。
试试这个:
// Wait until the DOM is loaded
window.addEventListener("DOMContentLoaded", function(){
// Get all the td elements in an array
var theCells = document.getElementsByTagName("td");
// Loop through each td
for(var i = 0; i < theCells.length; ++i){
// Set up a click event handler for the td
theCells[i].addEventListener("click", function(){
// Check to see if the td has the class attribute applied already
if(this.getAttribute("class") === "highlight"){
// If so, remove it
this.removeAttribute("class");
} else {
// If not, add it
this.setAttribute("class", "highlight");
}
});
}
});
td{border:1px solid black;}
.highlight {background:#ff0;}
<table>
<tr>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
</table>