表格行的背景色在单击时保持不变

时间:2019-07-01 19:44:49

标签: html css

我正在尝试单击时更改表格行的背景颜色。

我尝试将访问过的和焦点伪元素添加到tr标签中,但是输出仍然相同。

CMD
table {
  border-collapse: collapse;
  width: 100%;
}

th,
td {
  text-align: left;
  padding: 13px;
}

tr:nth-child(odd) {
  background-color: #f2f2f2;
}

tbody tr:hover {
  background-color: rgba(201, 228, 252) !important;
}

tbody tr:visited {
  background-color: rgba(201, 228, 252) !important;
}

我希望输出结果是,当我单击表格行时,该行保持突出显示,但单击时什么也没有发生。另外,我希望一次突出显示一行。

1 个答案:

答案 0 :(得分:1)

您需要使用javascript / jquery。这是使用JQuery的方法:

$('#tbl tr').on('click', function (){
    $('.clicked').removeClass('clicked');
	$(this).addClass('clicked');
});
table {
        border-collapse: collapse;
        width: 100%;
    }

      th, td {
        text-align: left;
        padding: 13px;
      }

      tr:nth-child(odd) {background-color: #f2f2f2;}

      tbody tr:hover {
        background-color: rgba(201, 228, 252) !important;
      }

      tbody tr.clicked {
        background-color: rgba(201, 228, 252) !important; 
      }    
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id = 'tbl' cellspacing="40">
      <thead id = 'heading'>
        <tr>
          <td colspan = "5" style="padding-right: 430px;"></td>
          <td style="padding-right: 300px;"></td>
          <td colspan = "2" style="padding-right: 260px;"></td>
          <td colspan = "2" style="padding-right: 215px;"></td>
        </tr>
      </thead>
      <div id = 'scrollbody'>
        <tbody>
          <tr>
            <td colspan = "5">
              Evelyn Henderson
            </td>
            <td>
              Reviewer
            </td>
            <td colspan = "2">
              (247) 262 5207
            </td>
            <td colspan = "2">
              evelyn-90@gmail.com
            </td>
          </tr>
          <tr>
            <td colspan = "5">
              Alfred Premkumar
            </td>
            <td>
              Reviewer
            </td>
            <td colspan = "2">
              (247) 262 5207
            </td>
            <td colspan = "2">
              apremk@gmail.com
            </td>
          </tr>
          <tr>
            <td colspan = "5">
              Surya Mamidyala
            </td>
            <td>
              Reviewer
            </td>
            <td colspan = "2">
              (247) 262 5207
            </td>
            <td colspan = "2">
              smamid@gmail.com
            </td>
          </tr>
          <tr>
            <td colspan = "5">
              Shrey Gupta
            </td>
            <td>
              Reviewer
            </td>
            <td colspan = "2">
              (247) 262 5207
            </td>
            <td colspan = "2">
              sgupta@gmail.com
            </td>
          </tr>
        </tbody>
      </div>
    </table>