Setting CSS pseudo-class rules from JavaScript

后端 未结 13 2003
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 01:01

I\'m looking for a way to change the CSS rules for pseudo-class selectors (such as :link, :hover, etc.) from JavaScript.

So an analogue of the CSS code: a:hove

13条回答
  •  天命终不由人
    2020-11-22 01:45

    You can't style a pseudo-class on a particular element alone, in the same way that you can't have a pseudo-class in an inline style="..." attribute (as there is no selector).

    You can do it by altering the stylesheet, for example by adding the rule:

    #elid:hover { background: red; }
    

    assuming each element you want to affect has a unique ID to allow it to be selected.

    In theory the document you want is http://www.w3.org/TR/DOM-Level-2-Style/Overview.html which means you can (given a pre-existing embedded or linked stylesheet) using syntax like:

    document.styleSheets[0].insertRule('#elid:hover { background-color: red; }', 0);
    document.styleSheets[0].cssRules[0].style.backgroundColor= 'red';
    

    IE, of course, requires its own syntax:

    document.styleSheets[0].addRule('#elid:hover', 'background-color: red', 0);
    document.styleSheets[0].rules[0].style.backgroundColor= 'red';
    

    Older and minor browsers are likely not to support either syntax. Dynamic stylesheet-fiddling is rarely done because it's quite annoying to get right, rarely needed, and historically troublesome.

提交回复
热议问题