taquaki-satwo
11/27/2017 - 3:05 PM

ストライプテーブル JavaScript

ストライプテーブル JavaScript

@use postcss-cssnext;

th, td {
  padding: 1em;
}

th {
  background: #222;
  color: white;
}

tr {
  &:nth-child(even) {
    background: #f2f2f2;
  }
  
  &:nth-child(odd) {
    background: #ccc;
  }
}

.hover {
  background: #aaf!important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
const $rows = document.querySelector('tbody').rows;
const $td = document.querySelectorAll('tbody td');

const addClass = (el) => {
  el.classList.add('hover');
}

const removeClass = (el) => {
  el.classList.remove('hover');
}

Array.from($rows).forEach(function(el) {
  el.addEventListener('mouseover', function() {
    addClass(this);
  }, false);
  el.addEventListener('mouseout', function() {
    removeClass(this);
  }, false);
});

Array.from($td).forEach(function(el) {
  el.addEventListener('mouseover', function() {
    for (var 1=0; i<$rows.length; i++) {
      addClass($rows[i].cells[this.cellIndex]);
    }
  }, false);
  el.addEventListener('mouseout', function() {
    for (var 1=0; i<$rows.length; i++) {
      removeClass($rows[i].cells[this.cellIndex]);
    }
  }, false);
});

ストライプテーブル JavaScript

A Pen by Takaaki Sato on CodePen.

License.

table#test
  thead
    tr
      th no
      th name
      th content
  tbody
    - for (var i=1; i<=5; i++)
      tr
        td #{i}
        td name #{i}
        td content #{i}