更改:使用JavaScript悬停CSS属性 [英] Change :hover CSS properties with JavaScript
问题描述
我需要找到一种方法来更改CSS:使用JavaScript来悬停属性。
I need to find a way to change CSS :hover properties using JavaScript.
例如,假设我有这个HTML代码:
For example, suppose I have this HTML code:
<table>
<tr>
<td>Hover 1</td>
<td>Hover 2</td>
</tr>
</table>
和以下CSS代码:
table td:hover {
background:#ff0000;
}
我想使用JavaScript来更改< td& hover属性to,say,background:#00ff00。知道我可以使用JavaScript访问样式背景属性:
I would like to use JavaScript to change the <td> hover properties to, say, background:#00ff00. know I could access the style background property using JavaScript as:
document.getElementsByTagName("td").style.background="#00ff00";
但我不知道一个JavaScript的等价物:hover。如何使用JavaScript更改这些< td>的:hover背景?
But I don't know of a JavaScript equivalent for :hover. How do I change these <td>'s :hover background using JavaScript?
非常感谢您的帮助。
推荐答案
伪类(如:hover
)从不指元素,而是指满足样式表条件的任何元素规则。您需要编辑样式表规则,添加新规则,或者添加一个新的样式表,其中包含新的:hover
rule。
Pseudo classes (like :hover
) never refer to an element, but to any element that satisfies the conditions of the stylesheet rule. You need to edit the stylesheet rule, append a new rule, or add a new stylesheet that includes the new :hover
rule.
var css = 'table td:hover{ background-color: #00ff00 }';
style = document.createElement('style');
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
document.getElementsByTagName('head')[0].appendChild(style);
这篇关于更改:使用JavaScript悬停CSS属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!