Javascript 如何使用java脚本更改表格中单元格的背景颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11517150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change background color of cell in table using java script
提问by Kasma
I need to change background color of single cell in table using java script.
我需要使用 java 脚本更改表格中单个单元格的背景颜色。
During document i need style of all cell should be same ( so used style sheet to add this. ) , but on button click i need to change color of first cell.
在文档期间,我需要所有单元格的样式都应该相同(因此使用样式表来添加它。),但是在单击按钮时,我需要更改第一个单元格的颜色。
following is the sample code
以下是示例代码
<html lang="en">
<head>
<script type="text/javascript" >
function btnClick()
{
var x = document.getElementById("mytable").cells;
x[0].innerHTML = "i want to change my cell color";
x[0].bgColor = "Yellow";
}
</script>
</head>
<style>
div
{
text-align: left;
text-indent: 0px;
padding: 0px 0px 0px 0px;
margin: 0px 0px 0px 0px;
}
td.td
{
border-width : 1px;
background-color: #99cc00;
text-align:center;
}
</style>
<body>
<div>
<table id = "mytable" width="100%" border="1" cellpadding="2" cellspacing="2" style="background-color: #ffffff;">
<tr valign="top">
<td class = "td"><br /> </td>
<td class = "td"><br /> </td>
</tr>
<tr valign="top">
<td class = "td"><br /> </td>
<td class = "td"><br /> </td>
</tr>
</table>
</div>
<input type="button" value="Click" OnClick = "btnClick()">
</body>
</html>
回答by nnnnnn
Try this:
尝试这个:
function btnClick() {
var x = document.getElementById("mytable").getElementsByTagName("td");
x[0].innerHTML = "i want to change my cell color";
x[0].style.backgroundColor = "yellow";
}
Set from JS, backgroundColor
is the equivalent of background-color
in your style-sheet.
从 JS 设置,backgroundColor
相当于background-color
在您的样式表中。
Note also that the .cells
collection belongs to a table row, not to the table itself. To get all the cells from all rows you can instead use getElementsByTagName()
.
另请注意,.cells
集合属于表行,而不是表本身。要从所有行中获取所有单元格,您可以改为使用getElementsByTagName()
.
回答by Thilini
<table border="1" cellspacing="0" cellpadding= "20">
<tr>
<td id="id1" ></td>
</tr>
</table>
<script>
document.getElementById('id1').style.backgroundColor='#003F87';
</script>
Put id for cell and then change background of the cell.
为单元格输入 id,然后更改单元格的背景。
回答by user3029797
document.getElementById('id1').bgColor = '#00FF00';
seems to work. I don't think .style.backgroundColor
does.
似乎工作。我不认为.style.backgroundColor
。