By adding an attribute or type selector to the <tr> element, you can use CSS settings to implement a two-color table. However, if the table is very long, it is really troublesome to add elements one by one. In addition, such code is not easy to maintain. Therefore, the better method is to use JS. In fact, in the webpage special effects of the past few days, we have also published such an example, "effect of changing colors of table interlace".
The principle is actually very simple: Use getElementsByTagName to get all the <tr> elements, and then add background colors for the <tr> elements of the odd and even items respectively.
Copy to ClipboardReference: [www.bkjia.com] <script type = "text/javascript">
Function color (){
// Set the header to purple
Var th = document. getElementById ("th ");
Th. style. background = "violet"
// 1. Obtain all <tr> Elements
Var trs = document. getElementsByTagName ("tr ");
Var I;
For (I = 1; I <trs. length; I ++ ){
// 2. Change the background color of the <tr> element.
If (I % 2 = 0 ){
Trs [I]. style. background = "yellow ";
} Else {
Trs [I]. style. background = "olive ";
}
}
}
Window. onload = color;
</Script>
Let's take a look at the effect:
<Html>
Tip: the code can be modified before running!