乐趣区

关于javascript: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++) {
      // 2. 给每个元素增加事件
      tr[i].onmouseover = function () {
        // 3. 排他,先对立去除所有元素的款式,for(var j = 0; j < tr.length; j++) {tr[j].style.backgroundColor = ''
        }
        // 4. 排他,再给以后项设置款式
        this.style.background = 'hotpink'
      }
    }
  </script>
</body>
</html>
退出移动版