避免使用 jQuery 突出显示所有行和列

Avoid highlighting all rows and columns with jQuery

我在 Twitter Bootstrap 中为我的 table 使用了下面的 jQuery:

$('td').mouseover(function () {
   $(this).siblings().css('background-color', '#EAD575');
   var ind = $(this).index();
   $('td:nth-child(' + (ind + 1) + ')').css('background-color', '#EAD575');
});
$('td').mouseleave(function () {
   $(this).siblings().css('background-color', '');
   var ind = $(this).index();
   $('td:nth-child(' + (ind + 1) + ')').css('background-color', '');
});

我在网站上找到了这段代码,我必须承认,它工作得很好......

...但是可以稍微调整一下,这样它也不会针对选定的行 and/or 列。

例如忽略 ID 为 'nohover'

的 row/column

这可能吗?这样做的原因是我有大约 3 或 4 个不应突出显示的合并行,因为它看起来 "weird".

任何人都知道这是否可能,如果可能的话;如何?

$().not('.nohover') 应该可以做到

$('td').mouseover(function () {
    $(this).siblings().not('.nohover').css('background-color', '#EAD575');
    var ind = $(this).index();
    $('td:nth-child(' + (ind + 1) + ')').not('.nohover').css('background-color', '#EAD575');
});
$('td').mouseleave(function () {
    $(this).siblings().css('background-color', '');
    var ind = $(this).index();
    $('td:nth-child(' + (ind + 1) + ')').not('.nohover').css('background-color', '');
});

https://jsfiddle.net/cd54pqdx/1/

更简洁的方法是更多地依赖外部 CSS。您可以添加具有该背景颜色的 CSS class,而不是使用内联 CSS 更改背景颜色。只需确保您的 .no-hover class 将背景颜色设置为透明(或任何默认背景颜色适用于您的 table 单元格)。

由于 CSS 级联,您可以将 .no-hover class 放在样式表中新的 class 下方,并且 no-hover class 将优先.

代码将从

$('td').mouseover(function () {
   $(this).siblings().css('background-color', '#EAD575');
   var ind = $(this).index();
   $('td:nth-child(' + (ind + 1) + ')').css('background-color', '#EAD575');
});
$('td').mouseleave(function () {
   $(this).siblings().css('background-color', '');
   var ind = $(this).index();
   $('td:nth-child(' + (ind + 1) + ')').css('background-color', '');
});

$('td').mouseover(function () {
   $(this).siblings().addClass('active-hover');
   var ind = $(this).index();
   $('td:nth-child(' + (ind + 1) + ')').addClass('active-hover');
});
$('td').mouseleave(function () {
   $(this).siblings().removeClass('active-hover');
   var ind = $(this).index();
   $('td:nth-child(' + (ind + 1) + ')').removeClass('active-hover');
});

(将 active-hover 更改为您决定悬停的任何内容 class 以命名)

我会避免使用 CSS3 :not 选择器,因为 <=IE8

不支持它