使用jQuery,您可以在突出显示脚本之前动态地将<colgroup></colgroup>
添加到每个表格。喜欢的东西 -
if($("table > colgroup").length == 0){ // If the table does not have <colgroup></colgroup>
var colCount = 0;
$('tr:nth-child(1) td').each(function() { // Get the count of table columns
if ($(this).attr('colspan')) { // if there is a <td colspan>
colCount += +$(this).attr('colspan');
} else {
colCount++;
}
});
var colgroupList = '';
for (i=0;i<colCount;i++){ // Add a <colgroup></colgroup> for each <td>
colgroupList += '<colgroup></colgroup>';
}
$("table").prepend(colgroupList);
}
$("table").delegate('td','mouseover mouseleave', function(e) {
...
的jsfiddle例如http://jsfiddle.net/BGR22/1/
编辑
如果你有一个页面上的多个表,你需要添加一个选择器仅获取父表 -
var $table = $(this).closest("table");
所以现在你的$("table").delegate()
看起来像
$("table").delegate('td','mouseover mouseleave', function(e) {
var $table = $(this).closest("table");
if (e.type == 'mouseover') {
$(this).parent().addClass("hover");
$table.children("colgroup").eq($(this).index()).addClass("hover");
} else {
$(this).parent().removeClass("hover");
$table.children("colgroup").eq($(this).index()).removeClass("hover");
}
});
更新的jsfiddle - http://jsfiddle.net/BGR22/3/
,并与3个表 - http://jsfiddle.net/BGR22/4/
这是很整齐!但是,在具有多个表格的页面上尝试此操作后,悬停会针对每列进行操作。见http://jsfiddle.net/BGR22/2/ – davewoodhall
我已经更新了一个选择器,只有当前的表,更新jsFiddle。 – Sean