js表格实现隔行换色(变量控制)

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    table,th,td {
      border-collapse: collapse;
      border: 1px solid #333;
      padding: 10px;
    }
  </style>
</head>
<body>
  <table>
    <tr><th>1</th><th>2</th><th>3</th></tr>
    <tr><td>a</td><td>b</td><td>c</td></tr>
    <tr><td>a</td><td>b</td><td>c</td></tr>
    <tr><td>a</td><td>b</td><td>c</td></tr>
    <tr><td>a</td><td>b</td><td>c</td></tr>
  </table>

  <script>
    var tr = document.querySelectorAll('tr')
    // 1.先遍历获取每个元素
    for(var i = 0; i < tr.length; i++) {
      // 偶数行和奇数行颜色区别
      if (i % 2 === 0) {
        tr[i].style.backgroundColor = 'white'
      }else {
        tr[i].style.backgroundColor = 'gray'
      }
      // 2.设置变量保存当前行的颜色
      var tr_color;

      // 3.给所有项绑定鼠标悬停事件
      tr[i].onmouseover = function () {
        // 鼠标悬停时将当前项的背景色赋值给变量
        tr_color = this.style.backgroundColor
        // 鼠标悬停时更改当前项背景颜色
        this.style.backgroundColor = 'hotpink'
      }
      // 4.给所有项绑定鼠标移出事件
      tr[i].onmouseout = function () {
        // 鼠标移出时将变量保存的背景色重新赋值给当前项
        this.style.backgroundColor = tr_color
      }
    }
  </script>
</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值