一、思路:循环+条件语句
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>隔行变色</title>
<style type="text/css">
.list{
list-style: none;
}
.list li{
background:red;
}
</style>
</head>
<body>
<ul class="list">
<li>彼黍离离,彼稷之苗。</li>
<li>行迈靡靡,中心摇摇。</li>
<li>知我者,谓我心忧;不知我者,谓我何求。</li>
<li>悠悠苍天,此何人哉?</li>
<li>彼黍离离,彼稷之穗。</li>
<li>行迈靡靡,中心如醉。</li>
<li>彼黍离离,彼稷之苗。</li>
<li>行迈靡靡,中心摇摇。</li>
</ul>
<script type="text/javascript">
var oLis=document.querySelectorAll('li');
for(var i=0;i<oLis.length;i++){
oLis[i].index=i;
console.log(oLis[i].index);
if(i%2==0){
oLis[i].style.backgroundColor='grey';//偶数行背景色为灰色
oLis[i].bg='grey';//用bg记录当前背景色
}else{
oLis[i].style.backgroundColor='rgb(250,240,190)';
oLis[i].bg='rgb(250,240,190)';
}
oLis[i].index=i;
oLis[i].onmouseover=function(){
oLis[this.index].style.backgroundColor='white';//鼠标移上,当前行背景色变白
};
oLis[i].onmouseout=function(){
oLis[this.index].style.backgroundColor=this.bg;//鼠标移出,当前行背景色变回原来颜色
};
/* //点击背景变色
oLis[i].onclick=function(){
oLis[this.index].style.backgroundColor='white';
};*/
}
</script>
</body>
</html>