Changing a CSS rule-set from Javascript

前端 未结 8 1003
甜味超标
甜味超标 2020-11-22 04:54

Is it possible to make changes to a CSS rule-set dynamically (i.e. some JS which would change a CSS rule-set when the user clicks a widget)

This particular CSS rule-

相关标签:
8条回答
  • 2020-11-22 05:57

    I tried the code via link from @alex-gyoshev comment, but it dosn't work

    1. it fails on the CSS rules with Google fonts in Chrome
    2. it fails on FireFox security checks

    So I changed it slightly, but deleted delete functionality since it wasn't needed for me. Checked in IE 11, FireFox 32, Chrome 37 and Opera 26.

    function getCSSRule(ruleName) { // Return requested style object
      ruleName = ruleName.toLowerCase(); // Convert test string to lower case.
      var styleSheet;
      var i, ii;
      var cssRule = false; // Initialize cssRule. 
      var cssRules;
      if (document.styleSheets) { // If browser can play with stylesheets
        for (i = 0; i < document.styleSheets.length; i++) { // For each stylesheet
          styleSheet = document.styleSheets[i];
          if (!styleSheet.href) {
            if (styleSheet.cssRules) { // Browser uses cssRules?
              cssRules = styleSheet.cssRules; // Yes --Mozilla Style
            } else { // Browser usses rules?
              cssRules = styleSheet.rules; // Yes IE style. 
            } // End IE check.
            if (cssRules) {
              for (ii = 0; ii < cssRules.length; ii++) {
                cssRule = cssRules[ii];
                if (cssRule) { // If we found a rule...
                  // console.log(cssRule);
                  if (cssRule.selectorText) {
                    console.log(cssRule.selectorText);
                    if (cssRule.selectorText.toLowerCase() == ruleName) { //  match ruleName?
                      return cssRule; // return the style object.
                    }
                  }
                }
              }
            }
          }
        }
      }
      return false; // we found NOTHING!
    }
    
    0 讨论(0)
  • 2020-11-22 05:58

    You can, but it's rather cumbersome. The best reference on how to do it is the following article: Totally Pwn CSS with Javascript (web archive link).

    I managed to get it to work with Firefox and IE - I couldn't in Chrome, though it appears that it supports the DOM methods.ricosrealm reports that it works in Chrome, too.

    0 讨论(0)
提交回复
热议问题