Felix Riesterer: Tabellenspalte bei :hover markieren

Beitrag lesen

Lieber Matthias,

vielleicht so (Demo)?

// old browsers
function toArray(collection) {
  return Array.prototype.slice.call(collection);
}

function markColumn (event) {
  var index = (event.target || event.srcElement).cellIndex,
      table = (event.target || event.srcElement);

  // get <table> ancestor
  while (!table.tagName.match(/^body|table$/i)) {
    table = table.parentNode;
  }

  if (table.tagName == "TABLE") {
    // do something to the cells
    toArray(
      table.querySelectorAll("td:not([colspan]), thead th")
    ).forEach(function (cell) {
      // correct column?
      if (cell.cellIndex === index) {
        // hover on or off?
        if (event.type == "mouseover") {
          // hover on
          cell.setAttribute("data-hover", "hover");
        } else {
          // hover off
          cell.removeAttribute("data-hover");
        }
      }
    });
  }
}

// make (almost) all table cells hover-able
toArray(
  document.querySelectorAll("td:not([colspan]), thead th")
).forEach(function (el) {
  el.addEventListener("mouseover", markColumn);
  el.addEventListener("mouseout", markColumn);
});

Das passende CSS wäre das hier:

[data-hover] {
  /* whatever */
  background: #faa;
}

Liebe Grüße

Felix Riesterer