JS---案例:表格隔行变色(鼠标划过背景色恢复)

案例:表格隔行变色(鼠标划过背景色恢复)

 

DOCTYPE html>
<html>

<head lang="en">
  <meta charset="UTF-8">
  <title>title>
  <style>
    * {
      padding: 0;
      margin: 0;
    }

    .wrap {
      width: 500px;
      margin: 100px auto 0;
    }

    table {
      border-collapse: collapse;
      border-spacing: 0;
      border: 1px solid #c0c0c0;
      width: 500px;
      cursor: pointer;
    }

    th,
    td {
      border: 1px solid #d0d0d0;
      color: #404060;
      padding: 10px;
      text-align: center;
    }

    th {
      background-color: #09c;
      font: bold 16px "微软雅黑";
      color: #fff;
    }

    td {
      font: 14px "微软雅黑";
    }

    tbody tr {
      background-color: pink;
    }
  style>
head>

<body>
  <div class="wrap">
    <table>
      <thead>
        <tr>
          <th>序号th>
          <th>姓名th>
          <th>课程th>
          <th>成绩th>
        tr>
      thead>
      <tbody id="j_tb">
        <tr>
          <td>
            1
          td>
          <td>柳岩td>
          <td>语文td>
          <td>100td>

        tr>
        <tr>
          <td>
            2
          td>
          <td>苍老师td>
          <td>日语td>
          <td>100td>
        tr>
        <tr>
          <td>
            3
          td>
          <td>凤姐td>
          <td>营销学td>
          <td>100td>
        tr>
        <tr>
          <td>
            4
          td>
          <td>芙蓉姐姐td>
          <td>数学td>
          <td>10td>
        tr>
        <tr>
          <td>
            5
          td>
          <td>佐助td>
          <td>英语td>
          <td>100td>
        tr>
        <tr>
          <td>
            6
          td>
          <td>卡卡西td>
          <td>体育td>
          <td>100td>
        tr>
        <tr>
          <td>
            7
          td>
          <td>乔峰td>
          <td>体育td>
          <td>100td>
        tr>
      tbody>
    table>
  div>
  <script src="common.js">script>
  <script>

    //获取所以的行
    var trs = my$("j_tb").getElementsByTagName("tr");
    for (var i = 0; i < trs.length; i++) {
      trs[i].style.backgroundColor = i % 2 == 0 ? "white" : "skyblue";
      //鼠标进入
      trs[i].onmouseover = mouseoverHandle;
      //鼠标离开
      trs[i].onmouseout = mouseoutHandle;
    }

    //鼠标进入的时候,先把设置后的颜色保存,等到鼠标离开再恢复即可
    var lastColor = "";
    function mouseoverHandle() {//鼠标进入
      lastColor = this.style.backgroundColor;
      this.style.backgroundColor = "pink";
    }
    function mouseoutHandle() {//鼠标进入
      this.style.backgroundColor = lastColor;
    }

  script>


body>

html>

你可能感兴趣的:(JS---案例:表格隔行变色(鼠标划过背景色恢复))