WEBデザインの勉強

初心者が1からWEBデザインを勉強するブログ。

オンマウスしたセルの列、行をハイライト

f:id:mmmmofu:20180403105346p:plain

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>table highlight</title>
  <link rel="stylesheet" href="style.css">
  <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  <script src="script.js"></script>
</head>
<body>
  <table class="data">
    <tr>
      <th></th>
      <th>Entry Header 1</th>
      <th>Entry Header 2</th>
      <th>Entry Header 3</th>
    </tr>
    <tr>
      <th>Entry Header 1</th>
      <td>Entry First Line 1</td>
      <td>Entry First Line 2</td>
      <td>Entry First Line 3</td>
    </tr>
    <tr>
      <th>Entry Header 2</th>
      <td>Entry Line 1</td>
      <td>Entry Line 2</td>
      <td>Entry Line 3</td>
    </tr>
    <tr>
      <th>Entry Header 3</th>
      <td>Entry Last Line 1</td>
      <td>Entry Last Line 2</td>
      <td>Entry Last Line 3</td>
    </tr>
  </table>
</body>
</html>
@charset "utf-8";

html, body, table, tr, th, td {
  margin: 0;
  padding: 0;
  font-family: "游ゴシック",YuGothic,"Helvetica","ヒラギノ角ゴ ProN W3", "Hiragino Kaku Gothic ProN", "メイリオ", Meiryo, "Helvetica Neue", Arial, sans-serif;
  line-height: 1.0;
  font-weight: 500;
}

.data {
  width: 810px;
  margin: 50px auto;
  border-collapse: collapse;
}

.data th {
  font-weight: bold;
}

.data th, .data td {
  position: relative;
  min-width: 200px;
  padding: 10px 0;
  text-align: center;
}

.data tr th:first-child {
  background: #eee;
}

.data tr:first-child th {
  border-top: 1px solid #000;
  border-bottom: 1px solid #000;
}

.data th.hover:after, .data td.hover:after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(255,115,115, 0.2);
}

.data td:hover {
  background: rgba(255,115,115, 0.6);
}
$(function(){
  $('.data th, .data td').hover(function() {
    //mousehover
    var index_th = $(this).index();
    var index_td = $(this).index() -1;
    $(this).not('tr:first-child th').siblings().addClass('hover');
    $(this).not('td').not('tr:first-child th:first-child').addClass('hover');
    if (index_th > 0) {
      $('.data tr:first-child th').eq(index_th).addClass('hover');
    }
    $(this).parents('.data').find('tr').each(function() {
      $(this).parents('.data').not(':first').find('th').eq(index_th).addClass('hover');
      if(index_td >= 0) {
        $(this).find('td').eq(index_td).addClass('hover');
      }
    });
  }, function() {
    //maoseout
    $('.data th, .data td').removeClass('hover');
  });
});