javascript 将鼠标悬停在同一表格中的另一行上时更改表格行的背景颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11692665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:01:47  来源:igfitidea点击:

Change background color of table row when hovering over another row in same table

javascripthtmlcss

提问by Mr Love

This is my first post here and I'm by no means a skilled HTML/CSS/JavaScript programmer so please bear with me if I'm not expressing myself clear enough - sorry if it's too wordy!

这是我在这里的第一篇文章,我绝不是一个熟练的 HTML/CSS/JavaScript 程序员,所以如果我表达的不够清楚,请原谅我 - 抱歉,如果它太罗嗦了!

I'm using a classic HTML table for tabular content and want to be able to change the background color of a different row than the one I'm currently hovering.

我正在使用经典的 HTML 表格作为表格内容,并且希望能够更改与我当前悬停的行不同的行的背景颜色。

The reason for this is that I have many tables that are divided into "sub-tables", each with its own header and one or more rows below. These sub-tables - all with the same styling - are however not coded as tables, instead I simply use different classes to style them (this mainly because they are so many and so small, with 1-6 rows each incl header).

这样做的原因是我有很多表被分成“子表”,每个表都有自己的标题和下面的一行或多行。这些子表 - 都具有相同的样式 - 但是没有编码为表,而是我只是使用不同的类来设置它们的样式(这主要是因为它们太多太小,每个包含 1-6 行包括标题)。

What I want to do is that once you hover any of the sub-tables both its header and the row you're currenty pointing at should change background color (the latter easily achived with CSS). Thanks to a JavaScript found online I've managed to achive this - see sample codewhich probably explains this better, see also the code below - however that requires a unique ID for each sub-header. (Note that each sub-table uses a separate tbody - if the onMouseoverevent was instead applied to each row the color of the sub-header would flicker/go on and off when hovering from one row to another - this never happens with CSS but only with JavaScript - plus creating much more code, of course.)

我想要做的是,一旦您将任何子表悬停,其标题和您当前指向的行都应该更改背景颜色(后者可以通过 CSS 轻松实现)。感谢在网上找到的 JavaScript,我设法实现了这一点 - 请参阅示例代码,它可能更好地解释了这一点,另请参阅下面的代码 - 但是这需要每个子标题的唯一 ID。(请注意,每个子表都使用一个单独的 tbody - 如果将onMouseover事件改为应用于每一行,则子标题的颜色会在从一行悬停到另一行时闪烁/继续闪烁 - 这在 CSS 中不会发生,但只有使用 JavaScript - 当然还要创建更多的代码。)

Instead of having to assign unique IDs to each sub-header I'd like a solution which instead uses the classes, seeing as each sub-table uses the same ones (I'd of course assign a class to tbodythen). I suppose the tricky part with this may be to ensure that just the header of the current sub-table is affected and not all at the same time. If it's easier to create a solution where each sub-table is in fact coded as a separate table (which may also be better from a semantic point of view?) then please do so. Even better would of course be if the JavaScript applied the onMouseoveretc events by itself, so that I didn't have to put that into the inline code of each sub-table - I've seen that this can be done for buttons etc so I suppose it'd be possible for this to.

我不需要为每个子标题分配唯一的 ID,我想要一个使用类的解决方案,因为每个子表都使用相同的子表(我当然会分配一个类tbody)。我想这个棘手的部分可能是确保只有当前子表的标题受到影响,而不是同时受到影响。如果创建一个解决方案更容易,其中每个子表实际上都被编码为一个单独的表(从语义的角度来看这也可能更好?),那么请这样做。当然,如果 JavaScript 自己应用onMouseoveretc 事件会更好,这样我就不必将其放入每个子表的内联代码中 - 我已经看到这可以用于按钮等,所以我假设这是可能的。

I've never used jQuery so a pure JavaScript solution would be much preferred.

我从未使用过 jQuery,因此更喜欢纯 JavaScript 解决方案。

For the sample code again please see my fiddle

对于示例代码,请参阅我的小提琴

Many thanks for any input!

非常感谢您的任何意见!

The JavaScript:

JavaScript:

function changeTo(myId) { document.getElementById(myId).className='sub-header-highlight'; }
function changeBack(myId) { document.getElementById(myId).className='sub-header'; }

The CSS:

CSS:

thead { color: #FFF; background: #000; }
.sub-header { color: #FFF; font-weight: bold; background: #F00; }
.sub-header-highlight { color:# FFF; font-weight: bold; background: #0F0; }
tr.sub-header:hover { background: #0F0; } /* if JS turned off */

.sub-row1 { color: #000; background: #FFF; }
.sub-row2 { color: #000; background: #EEE; }
tr.sub-row1:hover, .sub-row2:hover { background: #FF0; }

Part of the HTML:

部分 HTML:

<tbody onMouseover="changeTo('sub1');" onMouseout="changeBack('sub1');">
   <tr class="sub-header" id="sub1">
      <td>Sub-Header 1</td>
   </tr>
   <tr class="sub-row1">
      <td>Contents of row 1</td>
   </tr>
   <tr class="sub-row2">
      <td>Contents of row 2</td>
   </tr>
   <tr class="sub-row1">
      <td>Contents of row 3</td>
   </tr>
</tbody>

采纳答案by ErikE

You can greatly simplify both your HTML markup and CSS, and there is no need to use Javascript.

您可以极大地简化 HTML 标记和 CSS,并且无需使用 Javascript。

  • First, all the classes can come out except for your alternate row styling (unless you care nothing for IE 8 and below, in which case you can take out the IE conditional CSS and the class names. See the browser CSS selector compatibility chart.)
  • Second, change each tdinside a sub-header to a th.
  • Third, use the :hoverpseudo-selector on the parent tbodyto style the thas specified.
  • 首先,除了你的交替行样式之外,所有的类都可以出现(除非你对 IE 8 及以下版本毫不关心,在这种情况下你可以取出 IE 条件 CSS 和类名。请参阅浏览器 CSS 选择器兼容性图表。)
  • 其次,将td子标题中的每个更改为th.
  • 第三,使用:hover父级上的伪选择器tbody来设置th指定的样式。

See this working in a jsfiddle, tested to work perfectly in IE 7 and Firefox 14.

在 jsfiddle 中查看此工作,经测试可在 IE 7 和 Firefox 14 中完美运行。

Here is the CSS:

这是CSS:

table { border-collapse:collapse; }
thead { color: #FFF; background-color: #000; }

tbody th { color: #FFF; font-weight: bold; background-color: #F00; text-align:left; }
tbody:hover th { background: #0F0; }

tbody tr:nth-child(odd) { background-color:#EEE; }
tbody tr:hover td { background: #FF0; }

Style Notes:

样式说明:

  • The CSS property "background" expects more than just color, and will reset the other properties as well. Use "background-color" when that's all you want to style.
  • The extra tdon the tr:hoveris required in order for specificity rules to make IE give it a higher precedence than the special coloring for odd rows.
  • The "odd" rows are really the even ones of the data, because the sub-header consumes the first odd row.
  • Use CSS border-collapse:collapseinstead of cellspacingdirectly on the table.
  • CSS 属性“背景”不仅仅需要颜色,还会重置其他属性。当您只想设置样式时,请使用“背景颜色”。
  • 需要额外tdtr:hover,以便特殊性规则使 IE 赋予它比奇数行的特殊着色更高的优先级。
  • “奇数”行实际上是数据的偶数行,因为子标题消耗了第一个奇数行。
  • 使用 CSSborder-collapse:collapse而不是cellspacing直接在表格上。

I had to put the conditional CSS for IE in the HTML section of the fiddle since it must be outside the styletag.

我不得不将 IE 的条件 CSS 放在小提琴的 HTML 部分,因为它必须在style标签之外。

<!--[if lte IE 8]>
<style type="text/css">
  tbody tr.odd { color: #000; background: #EEE; }
</style>
<![endif]-->

And here's the HTML. See how clean it is now?

这是 HTML。看看现在有多干净?

<table>
   <thead>
      <tr>
         <th>MAIN HEADER</th>
      </tr>
   </thead>
   <tbody>
      <tr>
         <th>Sub-Header 1</th>
      </tr>
      <tr>
         <td>Contents of row 1</td>
      </tr>
      <tr class="odd">
         <td>Contents of row 2</td>
      </tr>
      <tr>
         <td>Contents of row 3</td>
      </tr>
   </tbody>
   <tbody>
      <tr>
         <th>Sub-Header 2</th>
      </tr>
      <tr>
         <td>Contents of row 1</td>
      </tr>
   </tbody>
   <tbody>
      <tr>
         <th>Sub-Header 3</th>
      </tr>
      <tr>
         <td>Contents of row 1</td>
      </tr>
      <tr class="odd">
         <td>Contents of row 2</td>
      </tr>
   </tbody>
</table>

Finally, I realize the colors were probably just examples, so may I suggest that bright primary colors are not going to work well with human cognitive response? You could go for a sort of highlighting effect instead. See a working examplethat I put together for you, using colors that are (to my eye) more pleasing. See how the section kind of "glows" when you hover over it? Beautiful!

最后,我意识到颜色可能只是例子,所以我可以建议明亮的原色不能很好地适应人类的认知反应吗?您可以改为使用一种突出显示效果。查看我为您整理的一个工作示例,使用(在我看来)更令人愉悦的颜色。当您将鼠标悬停在它上面时,看看该部分如何“发光”?美丽的!

Example of prettier table

更漂亮的表格示例

Note: In IE8 and before, there will be an extra border on the right side. If you have a multi-column table and you like the inside border thing and want to support IE8 and below, you'll need to add a class to the last cell in each row so it can have its right border removed.

注意:在 IE8 及之前版本,右侧会多出一个边框。如果您有一个多列表格并且您喜欢内部边框的东西并希望支持 IE8 及以下版本,则需要向每行的最后一个单元格添加一个类,以便可以删除其右边框。

回答by David says reinstate Monica

You can achieve this with pure CSS (with the usual browser-compatibility provisos), so assuming you're using a relatively modern Chrome, Safari, Firefox, Opera or, possibly, IE 9 (or greater):

您可以使用纯 CSS(具有通常的浏览器兼容性条款)来实现这一点,因此假设您使用的是相对现代的 Chrome、Safari、Firefox、Opera 或 IE 9(或更高版本):

tbody:hover tr.sub-header {
    background-color: #0f0;
}

tbody tr.sub-row:hover {
    background-color: #f90;
}?

JS Fiddle demo(obviously, adapt the colours to your taste; these were just for the purposes of a demonstration).

JS Fiddle 演示(显然,根据您的口味调整颜色;这些仅用于演示目的)。

It is, of course, worth mentioning that some browsers might not show the trelement's background-color(since it displays behindthe background-colorof the tdelements), in that case you might need to amend the selectors to target the relevant tdelements instead:

这是当然,值得一提的是某些浏览器可能不会显示tr元素的background-color(因为它显示背后background-color中的td元素),在这种情况下,你可能需要修改选择的目标相关的td元素,而不是:

tbody:hover tr.sub-header td {
    background-color: #0f0;
}

tbody tr.sub-row:hover td {
    background-color: #f90;
}?