Change :hover CSS properties with JavaScript

Posted dazzlinglight

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Change :hover CSS properties with JavaScript相关的知识,希望对你有一定的参考价值。

I need to find a way to change CSS :hover properties using javascript.

For example, suppose I have this html code:

<table>
  <tr>
    <td>Hover 1</td>
    <td>Hover 2</td>
  </tr>
</table>

And the following CSS code:

table td:hover {
background:#ff0000;
}

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";

But I don‘t know of a JavaScript equivalent for :hover. How do I change these <td>‘s :hover background using JavaScript?


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 ruleappend a new rule, or add a new stylesheet that includes the new :hover rule.

var css = ‘table td:hover{  padding: 0px; border: 0px; color: rgb(48, 51, 54);">;
style = document.createElement(‘style‘);

if (style.styleSheet) {
    style.styleSheet.cssText = css;
} else {
    style.appendChild(document.createTextNode(css));
}

document.getElementsByTagName(‘head‘)[0].appendChild(style);

以上是关于Change :hover CSS properties with JavaScript的主要内容,如果未能解决你的问题,请参考以下文章

怎么让css里的li:hover改变里面的a

css问题(啥可以代替a:hover 事件)

css关于hover显示问题

css hover问题。以下代码为啥还是被遮挡了,请看代码

css 的area标签支持hover吗?

css里面的hover能不能影响其他id。不使用js时