jQuery仅在表格中突出显示所选列
我看到这篇文章突出显示偶数列,但我是否可以仅突出显示所选列?
这是他们使用的代码:
$("table.Table22 > tbody > tr > td:nth-child(even)").css("background","blue");
但我想:注意: class="highlight"
将在所选列上,所以如果我选择了第3列,则class="highlight"
将从第2列中删除并添加到第3列.jQuery需要添加类基于选定的列。
Cell 1:Heading Selected column so this should be highlighted Cell 3:Heading Cell 4:Heading Cell 5:Heading Cell 1:Row 1 Selected column so this should be highlighted Cell 3:Row 1 Cell 4:Row 1 Cell 5:Row 1 Cell 1:Row 2 Selected column so this should be highlighted Cell 3:Row 2 Cell 4:Row 2 Cell 5:Row 2
你可能想看一下jQuery tableHover插件来实现这个目的。 然后使用这样的东西
$('table.tbl').tableHover({ colClass: 'hover', clickClass: 'click', headCols: true, footCols: true });
编辑:
像这样的东西?
工作演示 – 单击任何单元格以突出显示该列
演示代码 –
$(function() { var rows = $('table.tbl tr'); rows.children().click(function() { rows.children().removeClass('highlight'); var index = $(this).prevAll().length; rows.find(':nth-child(' + (index + 1) + ')').addClass('highlight'); }); });
你有没有使用colgroups而不是为每个单元格添加类?
我最近才开始亲眼看到colgroups的力量,他们的工作方式如下:
.highlight { background-color: yellow; }
header1 header2 header3 header4 header5 cell a cell b cell c cell d cell e
这是我用于向我的表添加交叉头发效果的内容:
$('tbody td').hover(function() { $(this).closest('tr').find('td,th').addClass('highlight'); var col = $(this).index()+1; $(this).closest('table').find('tr :nth-child('+col+')').addClass('highlight'); }, function() { $(this).closest('tr').find('td,th').removeClass('highlight'); var col = $(this).index()+1; $(this).closest('table').find('tr :nth-child('+col+')').removeClass('highlight'); });
似乎在大型桌子上运行有点慢(突出显示滞后)。
如果在表格标题中创建链接,则可以执行以下操作:
$("table.tbl th a").click(function() { var colnum = $(this).closest("th").prevAll("th").length; $(this).closest("table").find("tr td").removeClass("highlight"); $(this).closest("table").find("tr td:eq(" + colnum + ")").addClass("highlight"); }
这会将点击链接下方的所有单元格设置为“突出显示”类。
当然,您仍应在CSS文件中设置正确的样式:
table.tbl tr .highlight { background-color: blue; }
如果你想支持colspan
和rowspan
,那么首先需要构建表格单元索引,即。 无论标记如何,都可以识别每一行中的单元格位置。 然后,您需要跟踪所有感兴趣的表格单元格的事件,并计算它们在矩阵中的偏移量以及共享垂直索引的列。
结果查找在以下动画中说明:
我编写了一个插件,用于触发列的wholly.mouseenter
和wholly.mouseleave
事件。 完全 。
你可以使用一个名为fully的插件。 您可以在这里阅读有关如何集成它的完整教程http://voidtricks.com/wholly-jquery-plugin/