原理其实很简单:利用getElementsByTagName得到所有的
元素,然后分别为奇数项和偶数项的元素添加背景颜色。核心代码:
function color() {
//把表头设为紫色
var th = document.getElementById("th");
th.style.background = "violet"
//1.得到所有
元素var trs = document.getElementsByTagName("tr");
var i;
for(i = 1; i
//2.改变
元素的背景颜色if(i % 2 == 0) {
trs[i].style.background = "yellow";
} else {
trs[i].style.background = "olive";
}
}
}
window.onload = color;
全部代码:
双色表格function color() {
//把表头设为紫色
var th = document.getElementById("th");
th.style.background = "violet"
//1.得到所有
元素var trs = document.getElementsByTagName("tr");
var i;
for(i = 1; i
//2.改变
元素的背景颜色if(i % 2 == 0) {
trs[i].style.background = "yellow";
} else {
trs[i].style.background = "olive";
}
}
}
window.onload = color;
姓名 | 科目 | 成绩 |
---|---|---|
张三 | 语文 | 90 |
张三 | 数学 | 87 |
李四 | 数学 | 68 |
王五 | 英语 | 76 |