マウスオーバー【オンマウス】で表の行列の色が変わるjqueryサンプル

マウスオーバーした時に表の行列の背景色を変えるjqueryのメモ。

行の色だけでなく、列の色も変わるようにしたかったので。

今回はjqueryを使った方法です。

jqueryの場合

実際の見え方

発売日題名おススメ度
2017/11/26サンプル1★★★☆
2017/12/20サンプル2★★☆☆
2018/12/25サンプル3★★★★

サンプルコード

HTMLコード

<table id="hover_sample">

  <tr><th>発売日</th><th>題名</th><th>おススメ度</th></tr>

  <tr><td>2017/11/26</td><td>サンプル1</td><td>★★★☆</td></tr>
  <tr><td>2017/12/20</td><td>サンプル2</td><td>★★☆☆</td></tr>
  <tr><td>2018/12/25</td><td>サンプル3</td><td>★★★★</td></tr>

</table>

※特定の表の色を変更するためにIDを指定しています。

javascriptコード

$(function () {
  $("table#hover_sample td").hover(function () {
    var idx = $(this).index() + 1;
    var tds = $(this).closest("table#hover_sample").find("td:nth-child(" + idx + ")");
    tds.css("background-color", "aqua");
    $(this).css("background-color", "skyblue");
    $(this).siblings().css('background', 'aqua');
  }, function () {
    var idx = $(this).index() + 1
    var tds = $(this).closest("table#hover_sample").find("td:nth-child(" + idx + ")");
    tds.css("background-color", "");
    $(this).css("background-color", "");
    $(this).siblings().css('background', '');
 });
});

※特定の表の色を変更するためにIDを指定しています。

ちなみに、行の色を変えるだけならCSSでスタイルを指定するだけで可能です。

cssコード

tr:hover{background-color:darkblue;color:white;}