表格的隔行變色實(shí)現(xiàn)的方法也有多種,可以用CSS的選擇器來實(shí)現(xiàn),比如
:nth-of-type(odd){}/*奇數(shù)行*/
:nth-of-type(even){}/*偶數(shù)行*/
同樣運(yùn)用css背景的方法也可以實(shí)現(xiàn)。當(dāng)然了,利用js做的表格隔行變色是比較好的做法,因?yàn)榧嫒莺美溺琛R膊粡U話了,上代碼
<table>
<th>
<td>ID</td>
<td>Name</td>
<td>Age</td>
</th>
<tr>
<td>0</td>
<td>張三</td>
<td>20</td>
</tr>
<tr>
<td>1</td>
<td>李四</td>
<td>20</td>
</tr>
<table>
htm結(jié)構(gòu)如上面;js如下
<script>
var tab=document.getElementsByTagName("table")[0];
//js獲取表格的tbody和tr,td也可以用getElementsByTagName來獲取
//但是我們有更加簡(jiǎn)便的方法來獲取
var oldBgColor="";
//用來記錄移入時(shí)表格行的background
for(var i=0;i<tab.tBodies[0].rows.length;i++){
tab.tBodies[0].rows[i].style.background=i%2?"red":"orange";
tab.tBodies[0].rows[i].onmouseover=function(){
oldBgColor=this.style.background;
this.style.background="yellow";
}
tab.tBodies[0].rows[i].onmouseout=function(){
this.style.background=oldBgColor;
}
}
</script>
js內(nèi)置tBodies,rows,cells這些獲取表格的簡(jiǎn)便操作巍棱。如有錯(cuò)誤惑畴,歡迎糾正,互勵(lì)共勉航徙。