在鼠标悬停时更改 html 中的字体颜色和背景
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19794433/
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
Change font color and background in html on mouseover
提问by user613326
I'm using a small piece of inline HTML code to change the background of a cell color in a table on mouse hover. I use this on specific table cells only, so not all cells need this to happen.
我正在使用一小段内联 HTML 代码在鼠标悬停时更改表格中单元格颜色的背景。我仅在特定的表格单元格上使用它,因此并非所有单元格都需要发生这种情况。
<td bgcolor="#000000" onmouseover="this.bgColor='white'" onmouseout="this.bgColor='black'" >
This works nicely, but I would also like to change the font color.
这很好用,但我也想更改字体颜色。
So that it by default is a black cell with white text
所以默认情况下它是一个带有白色文本的黑色单元格
But on mouseover the bgcolor is white and the text is black, how should I do that ?
但是在鼠标悬停时 bgcolor 是白色的,文本是黑色的,我该怎么做?
回答by Sachin
It would be great if you use :hover
pseudo class over the onmouseover
event
如果您:hover
在onmouseover
事件上使用伪类,那就太好了
td:hover
{
background-color:white
}
and for the default styling just use
对于默认样式,只需使用
td
{
background-color:black
}
As you want to use these styling not over all the td
elements then you need to specify the class to those elements and add styling to that class like this
由于您不想在所有td
元素上使用这些样式,因此您需要为这些元素指定类并像这样向该类添加样式
.customTD
{
background-color:black
}
.customTD:hover
{
background-color:white;
}
You can also use :nth-child
selector to select the td elements
您还可以使用:nth-child
选择器来选择 td 元素
回答by dljve
Either do it with CSS like the other answers did or change the text style color directly via the onMouseOver and onMouseOut event:
要么像其他答案一样使用 CSS 执行此操作,要么直接通过 onMouseOver 和 onMouseOut 事件更改文本样式颜色:
onmouseover="this.bgColor='white'; this.style.color='black'"
onmouseover="this.bgColor='white'; this.style.color='black'"
onmouseout="this.bgColor='black'; this.style.color='white'"
onmouseout="this.bgColor='black'; this.style.color='white'"
回答by Bigood
You'd better use CSS for this:
您最好为此使用 CSS:
td{
background-color:black;
color:white;
}
td:hover{
background-color:white;
color:black;
}
If you want to use these styles for only a specific set of elements, you should give your td
a class(or an ID, if it's the only element which'll have that style).
如果您只想将这些样式用于一组特定的元素,您应该提供td
一个类(或一个ID,如果它是唯一具有该样式的元素)。
Example :
例子 :
HTML
HTML
<td class="whiteHover"></td>
CSS
CSS
.whiteHover{
/* Same style as above */
}
Here's a reference on MDNfor :hover
pseudo class.
下面是关于MDN参考的:hover
伪类。