方法一:
通过索引的方式比较low
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
</ul>
</body>
<script>
var oLis = document.getElementsByTagName('li');
oLis[0].style.background = 'blue'
oLis[1].style.background = 'red'
oLis[2].style.background = 'blue'
oLis[3].style.background = 'red'
oLis[4].style.background = 'blue'
oLis[5].style.background = 'red'
oLis[6].style.background = 'blue'
</script>
方法二
利用for 循环
<script>
var oLis = document.getElementsByTagName('li');
for (var i = 0; i < oLis.length; i++) {
//oLis[i].style.backgroundColor = 'red'
// 通过i来判断 i=0 第一行;i=1 第二行
// i%2 ==0 说明i是偶数 行是奇数行
// i%2 ==1 说明i是奇数 行是偶数行
if(i%2){
oLis[i].style.backgroundColor = 'red'
}
else{
oLis[i].style.backgroundColor = 'green'
}
</script>
方法三
利用switch循环
<script>
var oLis = document.getElementsByTagName('li');
switch (i % 2) {
case 0:
oLis[i].style.backgroundColor = 'green'
break
case 1:
oLis[i].style.backgroundColor = 'red'
break
}
</script>
方法四
利用三元 // 实现鼠标移上变色 移出变回原来的颜色
//点击li 弹出这是第xx行 背景颜色是xx
<script>
var oLis = document.getElementsByTagName('li');
olis[i].style.background = i%2 ? 'red':'green';
olis[i].myBg = this.style.background;
olis[i].myIndex = i;
olis[i].onmouseenter = function(){
this.style.background = 'gold'
}
olis[i].onmouseleave = function(){
this.style.background = this.myBg;
}
olis[i].onclick = function(){
alert(`这是第${this.myIndex} 背景颜色是${this.myBg}`)
}
}
</script>