使用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