JavaScript 如何改变 CSS :hover
属性?
例如:
HTML
<table>
<tr>
<td>Hover 1</td>
<td>Hover 2</td>
</tr>
</table>
CSS
table td:hover {
background:#ff0000;
}
如何使用 JavaScript 将 td :hover
属性修改为 background:#00ff00
?我知道我可以使用 JavaScript 访问样式背景属性:
document.getElementsByTagName("td").style.background="#00ff00";
但我不知道 .style
JavaScript 等同于 :hover
。
最佳答案
像:hover
这样的伪类从不引用元素,而是引用任何满足样式表规则条件的元素。您需要编辑样式表规则、附加新规则,或添加包含新:hover
规则的新样式表。
var css = 'table td:hover{ background-color: #00ff00 }';
var style = document.createElement('style');
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
document.getElementsByTagName('head')[0].appendChild(style);
关于javascript - 更改 :hover CSS properties with JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11371550/