使用js改变表格行的背景色

来源:互联网 发布:昆士兰it 编辑:程序博客网 时间:2024/06/05 19:19
<!doctype html>
<html>
<head>
<!--表格内外边框属性测试-->
<style>
td{
text-align:center;
width:100px;
height:30px;
}
</style>
<script>
function test(){
var rows=document.getElementById("table1").rows;//获取表格的所有行
for(var i=0;i<rows.length;i++){//遍历表格的所有行
if(i%2==0){//如果是偶数行
rows[i].style.backgroundColor="red";//更改偶数行的背景颜色
}
}
}
function test2(){
var rows=document.getElementById("table1").rows;
for(var i=0;i<rows.length;i++){
if(i%2!=0){
rows[i].style.backgroundColor="green";
}
}
}


</script>
<meta charset="UTF-8">
</head>
<body>
<table id="table1" cellspacing="1" cellpadding="1">
<tr>
<th>姓名</th><th>年龄</th><th>性别</th>
</tr>
<tr>
<td>奥巴马</td><td>50</td><td>男</td>
</tr>
<tr>
<td>川普</td><td>60</td><td>男</td>
</tr>
<tr>
<td>三胖</td><td>30</td><td>男</td>
</tr>
<tr>
<td>习近平</td><td>50</td><td>男</td>
</tr>
</table>
<input type="button" onclick="test()" value="测试外边框"><input type="button" value="测试内边框" onclick="test2()">
</body>
</html>
原创粉丝点击