HTML代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>隔行变色</title>
</head>
<link rel="stylesheet" href="css/index.css" />
<body>
<ul id="newBox">
<li>我是第一个li</li>
<li>我是第二个li</li>
<li>我是第三个li</li>
<li>我是第四个li</li>
<li>我是第五个li</li>
</ul>
<script>
//[context].getElementsByTagName([tagname]):
//在指定context范围之内,通过标签名获取一组元素(元素集合)
//集合和数组很相似,也是以数字索引作为属性名,
//有length属性储存长度,但不是数组,属于"类数组"
var newsBox = document.getElementById("newBox") ;
var newsList = newsBox.getElementsByTagName('li') ;
//1.循环所有获取的li,判断每一个;li的奇偶行,让其有不同的背景色
for(var i = 0 ; i < newsList.length ; i++){
//第一轮:i=0 操作第一个Li newsList[0]
//第二轮:i=1 操作第一个Li newsList[1]
var curLi = newsList[i] ;
//i = 0(偶数) 第一个LI 奇数行
//i = 1(奇数) 第二行LI 偶数行
//=>当前这一行的索引如果是偶数,那么它是奇数行,否则是偶数行
//偶数判断的标准:能被2整除(除2的余数为0)
var cc = i % 2 === 0 ?'#FFF':'#DDD' ;
curLi.style.background = cc;
//2.循环的时候给每个LI都绑定mouseover/mouseout事件
curLi.onmouseover = function(){
//this:当前操作的这个LI
this.style.background = "lightblue" ;
}
curLi.onmouseout = function(){
this.style.background = '#fff' ;
}
}
</script>
</body>
</html>
CSS代码:
*{
margin: 0;
padding: 0;
}
ul{
list-style: none;
}
#newBox{
box-sizing: border-box;
margin: 20px auto;
padding: 20px;
width: 300px;
border: 2px solid lightblue;
}
#newBox li{
line-height: 60px;
border-bottom: 1px dashed lightcoral;
cursor: pointer;
}
/*获取UI倒数第一个*/
#newBox li:nth-last-child(1){
border-bottom: none;
}
/*基于CSS实现*/
#newBox li:nth-child(even){
background: lightgray;
}
#newBox li:hover{
background: lightgreen;
}
效果图: