html - 如何将 CSS 应用于 2x2 <td> 类?

标签 html css html-table

我有 HTML 5x5 单元格的表格。悬停在任何 <td> 上时我需要更改 4 个单元格的 2x2 block 的背景。下面是更改当前行背景的代码。

td.1:hover, td.1:hover + td.1 {
    background:#eee;
}

我不知道如何像这样更改行中的背景:

http://i.stack.imgur.com/pezGA.png

最佳答案

仅使用 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 中为您想要的“悬停”类提供任何样式。

DEMO 1

但是,如果您想在每次将鼠标悬停在表格中的任何 TD 上时更改完全相同的 4 个 TD 的背景,这可以完全使用 CSS 完成。只需为要突出显示的 4 个单元格指定一个类名。例如,我们称这个类为“block2x2”。那么你的 CSS 是:

table:hover .block2x2 {
    background: #eee; // whatever background style you want
}

DEMO 2

关于html - 如何将 CSS 应用于 2x2 <td> 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16055852/

相关文章:

javascript - 在 D3 中格式化刻度

javascript - JS : Get Y Position of a String in Div

css - 根据angular js中的某些条件模糊背景图像

html - 点击第二个用户名或密码输入框,光标跳转到第一个

html - Q : Hovering In Html

javascript - 如何向 JSON 输出表添加 header ?

jquery - 搜索 HTML 表格

javascript - 根据所选选项显示 SQL 查询

html - 输入样式,无效时为什么不显示我的 block

jQuery 根据单击的按钮显示/隐藏表格行