如何使用java脚本更改表格中单元格的背景颜色 [英] How to change background color of cell in table using java script
问题描述
我需要使用java脚本更改表格中单个单元格的背景颜色。
在文档中,我需要所有单元格的样式应该相同(所以使用样式表添加此)。但按钮单击时,我需要更改第一个单元格的颜色。
以下是示例代码
< html lang =烯>
< head>
< script type =text / javascript>
函数btnClick()
{
var x = document.getElementById(mytable)。cells;
x [0] .innerHTML =我想改变我的细胞颜色;
x [0] .bgColor =黄色;
}
< / 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;
背景颜色:#99cc00;
text-align:center;
}
< / style>
< body>
< div>
< 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 =buttonvalue =ClickOnClick =btnClick()>
< / body>
< / html>
试试这个:
function btnClick(){
var x = document.getElementById(mytable)。getElementsByTagName(td);
x [0] .innerHTML =我想改变我的细胞颜色;
x [0] .style.backgroundColor =yellow;
从JS设置, backgroundColor
在您的样式表中相当于 background-color
。
还要注意 .cells
集合属于表行,而不属于表本身。要获取所有行的所有单元格,您可以改为使用 getElementsByTagName()
。
演示: http://jsbin.com/ekituv/edit#preview
I need to change background color of single cell in table using java script.
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>
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.
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()
.
Demo: http://jsbin.com/ekituv/edit#preview
这篇关于如何使用java脚本更改表格中单元格的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!