【问题标题】:How to apply CSS to 2x2 <td> classes?如何将 CSS 应用于 2x2 <td> 类?
【发布时间】:2013-04-17 18:14:54
【问题描述】:

我有 HTML 带有 5x5 单元格的表格。当悬停在任何&lt;td&gt; 上时,我需要更改 4 个单元格的 2x2 块的背景。这是更改当前行背景的代码。

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

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

【问题讨论】:

  • 如果没有 javascript,这是不可能的

标签: html css html-table


【解决方案1】:

仅使用 CSS,您只能影响 TD 的子代或下一个兄弟姐妹。即,您可以将背景扩展到您悬停的那个旁边的 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

【讨论】:

  • jqury 就是我需要的。谢谢。如果我需要标记更多单元格,请添加 t.next().addClass('hovered').next().addclass('hovered'); ?
  • @user2289809,是的,这将为悬停的 TD 的下两个兄弟姐妹提供“悬停”类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-19
  • 2011-01-03
  • 1970-01-01
  • 1970-01-01
  • 2014-05-07
  • 1970-01-01
相关资源
最近更新 更多