使用CSS设置表格隔行变色

html-css011

使用CSS设置表格隔行变色,第1张

在CSS中可使用:nth-child()选择器来实现表格隔行变色效果。:nth-child()选择器用于根据元素在一组兄弟中的位置来匹配元素;它匹配第n个子元素。语法:其中arg是表示匹配元素的模式的参数;它可以是一个数字(number)、一个关键字(odd 或 even)或一个函数式。想要隔行设置表格的行颜色需要使用到关键字(odd 或 even),下面就来介绍一下: ●  odd :表示位置为奇数的元素,即1,3,5等。 ●  even: 表示位置为偶数的元素,即2,4,6等。示例1: 为在表中交替的偶数行设置颜色 效果图:示例2: 为在表中交替的奇数行设置颜色 效果图: 更多 web开发 知识,请查阅 HTML中文网 !!

把下面的代码复制一下就OK了 ,这是div的例子

----------------------------------------------------------------------

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/htmlcharset=gb2312" />

<style>

div{ height:25px}

</style>

<title>无标题文档</title>

</head>

<body>

<div id=list>

<div>这是div</div>

<div>这是div</div>

<div>这是div</div>

<div>这是div</div>

<div>这是div</div>

</div>

<script type="text/javascript">

<!--

var colorArr = new Array("#cc0000","#cc00cc")

var s = 0

function listdown() {

var list = document.getElementById("list").getElementsByTagName("div")

for (var i=0i<list.length i++ )

{

list[i].style.backgroundColor = colorArr[s++]

if (s==colorArr.length)

{

s = 0

}

}

}

window.onload = listdown

//-->

</script>

</body>

</html>

--------------------------------------------------------------------

脚本解释:

-------------------------------------------------------------------

<script type="text/javascript">

<!--

var colorArr = new Array("#cc0000","#cc00cc") /*定义颜色数组*/

var s = 0

function listdown() {

var list = document.getElementById("list").getElementsByTagName("div") /*读取id为list里的div赋给list*/

for (var i=0i<list.length i++ )

{

list[i].style.backgroundColor = colorArr[s++] /*将colorArr颜色数组的第s个颜色值赋给list数组里第i个div的背景色

*/

if (s==colorArr.length) /*如果颜色数组长度等于s,使s值为0,这是为了实现颜色交替,前2个颜色交替完了,就开始下一组了*/

{

s = 0

}

}

}

window.onload = listdown/*页面加载时就调用此函数实现效果*/

//-->

</script>

--------------------------------------------------------------------

已经解释的很清楚了,div的都会了 li的 同理,把ul的id设为list,div换成li

。O了,还有不明白的Hi一下。

对了,我测试过了,firefox浏览器是不支持expression的。