JS 实现奇数偶数行颜色不同

HTML代码部分:

input type="button" value="隔行变色" id="btn"/>
<ul id="uu">
  <li>红旗</li>
  <li>五菱宏光</li>
  <li>奔驰</li>
  <li>兰博基尼</li>
  <li>哈弗</li>
  <li>奥拓</li>
  <li>奥迪</li>
  <li>悍马</li>
</ul>
<script src="common.js"></script>

JS代码部分:

my$("btn").onclick = function () {
    //获取所有的li标签
    var list = my$("uu").getElementsByTagName("li");
    for (var i = 0; i < list.length; i++) {
      list[i].style.backgroundColor = i % 2 == 0 ? "red" : "yellow";
    }
  };

common.js

/**
 * 根据id属性的值,返回对应的标签元素
 * @param id id属性的值,string类型的
 * @returns {Element} 元素对象
 */
function my$(id) {
    return document.getElementById(id);
}

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用以下代码实现: HTML: ```html <table id="myTable"> <thead> <tr> <th>姓名</th> <th>语文</th> <th>数学</th> <th>英语</th> <th>总分</th> </tr> </thead> <tbody> <tr> <td>张三</td> <td>90</td> <td>80</td> <td>70</td> <td></td> </tr> <tr> <td>李四</td> <td>85</td> <td>75</td> <td>65</td> <td></td> </tr> <tr> <td>王五</td> <td>95</td> <td>85</td> <td>75</td> <td></td> </tr> </tbody> </table> ``` CSS: ```css table { border-collapse: collapse; width: 100%; } th, td { border: 1px solid #ddd; text-align: center; padding: 8px; } th { background-color: #f2f2f2; } tr:nth-child(odd) { background-color: #f9a7b0; color: #fff; } tr:nth-child(even) { background-color: #a7c2f9; color: #fff; } ``` JavaScript: ```javascript var table = document.getElementById("myTable"); var rows = table.getElementsByTagName("tr"); for (var i = 1; i < rows.length; i++) { rows[i].onclick = function() { var scoreCells = this.getElementsByTagName("td"); var totalScore = 0; for (var j = 1; j < scoreCells.length - 1; j++) { totalScore += parseInt(scoreCells[j].innerHTML); } if (this.style.backgroundColor === "" || this.style.backgroundColor === "rgb(255, 255, 255)") { this.style.backgroundColor = "rgb(0, 0, 255)"; this.style.color = "#fff"; } else { this.style.backgroundColor = ""; this.style.color = ""; } scoreCells[scoreCells.length - 1].innerHTML = totalScore; } } ``` 这段代码会为表格中的每一添加点击事件,当点击某一时,会计算该除第一列和最后一列外的单元格中的总分,并将总分显示在该的最后一列中。同时,如果该奇数,则将背景设置为蓝,字体颜色设置为白;如果该偶数,则将背景设置为红,再次点击则取消背景和字体颜色设置

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值