我有 HTML
5x5 单元格的表格。悬停在任何 <td>
上时我需要更改 4 个单元格的 2x2 block 的背景。下面是更改当前行背景的代码。
td.1:hover, td.1:hover + td.1 {
background:#eee;
}
我不知道如何像这样更改行中的背景:
最佳答案
仅使用 CSS,您只能影响 TD 的 child 或下一个 sibling 。即,您可以将背景扩展到您悬停的对象旁边的 TD,但不能扩展到另一行。
要完成您想做的事情,您必须使用 JavaScript,因为您需要在 DOM 中上下移动,而 CSS 不允许您这样做。
例如,要使用 jQuery 做到这一点,请尝试这样的事情:
$('td').hover(function () {
var t = $(this),
index = t.index(); // the position of the TD in the row, so you can find the one below it
t.addClass('hovered'); // apply hovered class to this TD...
t.next().addClass('hovered'); // ...and to the TD next to it...
t.closest('tr').next().find('td:eq(' + index + ')').addClass('hovered').next().addClass('hovered'); // ...and to the 2 below
}, function () {
// remove the hovered class when no longer hovering
$(this).closest('table').find('td').removeClass('hovered');
});
然后在您的 CSS 中为您想要的“悬停”类提供任何样式。
但是,如果您想在每次将鼠标悬停在表格中的任何 TD 上时更改完全相同的 4 个 TD 的背景,这可以完全使用 CSS 完成。只需为要突出显示的 4 个单元格指定一个类名。例如,我们称这个类为“block2x2”。那么你的 CSS 是:
table:hover .block2x2 {
background: #eee; // whatever background style you want
}
关于html - 如何将 CSS 应用于 2x2 <td> 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16055852/