Solution qui gère colspan
J'ai une solution basée sur la correspondance du bord td
gauche du bord gauche du correspondant th
. Il doit gérer des colspans arbitrairement complexes.
J'ai modifié le cas de test pour montrer que l'arbitraire colspan
est géré correctement.
JS
$(function($) {
"use strict";
$(document).on('mouseover mouseout', 'td', function(event) {
var td = $(event.target).closest('td'),
th = thFromTd(td);
th.parent().find('.highlight').removeClass('highlight');
if (event.type === 'mouseover')
th.addClass('highlight');
});
function thFromTd(td) {
var ofs = td.offset().left,
table = td.closest('table'),
thead = table.children('thead').eq(0),
positions = cacheThPositions(thead),
matches = positions.filter(function(eldata) {
return eldata.left <= ofs;
}),
match = matches[matches.length-1],
matchEl = $(match.el);
return matchEl;
}
function cacheThPositions(thead) {
var data = thead.data('cached-pos'),
allth;
if (data)
return data;
allth = thead.children('tr').children('th');
data = allth.map(function() {
var th = $(this);
return {
el: this,
left: th.offset().left
};
}).toArray();
thead.data('cached-pos', data);
return data;
}
});
CSS
.highlight {
background-color: #EEE;
}
HTML
<table>
<thead>
<tr>
<th colspan="3">Not header!</th>
<th id="name" colspan="3">Name</th>
<th id="address">Address</th>
<th id="address">Other</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="2">X</td>
<td>1</td>
<td>Bob</td>
<td>J</td>
<td>Public</td>
<td>1 High Street</td>
<td colspan="2">Postfix</td>
</tr>
</tbody>
</table>