Setting CSS pseudo-class rules from JavaScript

后端 未结 13 1652
爱一瞬间的悲伤
爱一瞬间的悲伤 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

    A function to cope with the cross-browser stuff:

    addCssRule = function(/* string */ selector, /* string */ rule) {
      if (document.styleSheets) {
        if (!document.styleSheets.length) {
          var head = document.getElementsByTagName('head')[0];
          head.appendChild(bc.createEl('style'));
        }
    
        var i = document.styleSheets.length-1;
        var ss = document.styleSheets[i];
    
        var l=0;
        if (ss.cssRules) {
          l = ss.cssRules.length;
        } else if (ss.rules) {
          // IE
          l = ss.rules.length;
        }
    
        if (ss.insertRule) {
          ss.insertRule(selector + ' {' + rule + '}', l);
        } else if (ss.addRule) {
          // IE
          ss.addRule(selector, rule, l);
        }
      }
    };
    

提交回复
热议问题