Change a CSS stylesheet's selectors' prope

2019-06-13 16:17发布

Here's how we traditionally change the style of a recurring element.

Applying the style to each element

function changeStyle(selector, prop, val) {
  var elems = document.querySelectorAll(selector);
  Array.prototype.forEach.call( elems, function(ele) {
    ele.style[prop] = val;
  });
}

changeStyle('.myData', 'color', 'red');

Using classes to supersede the existing style

function addClass(selector, newClass) {
  var elems = document.querySelectorAll(selector);
  for (let i=0; i<elems.length; i++) {
    elems[i].classList.add(newClass);
  };
}

addClass('.myData', 'redText');

Instead, I want to change the actual stylesheet's selectors' properties (such as directly modifying a class). I don't want to loop through the elements that match my selector and apply the CSS directly nor add a modifier class to the elements.

1条回答
霸刀☆藐视天下
2楼-- · 2019-06-13 16:49
  1. Use an external stylesheet
  2. Identify its order on the page
  3. Modify the properties of the rules

Here's how to do that:

// ssMain is the stylesheet's index based on load order. See document.styleSheets. E.g. 0=reset.css, 1=main.css.
var ssMain = 1;
var cssRules = (document.all) ? 'rules': 'cssRules';

function changeCSSStyle(selector, cssProp, cssVal) {

  for (i=0, len=document.styleSheets[ssMain][cssRules].length; i<len; i++) {

    if (document.styleSheets[ssMain][cssRules][i].selectorText === selector) {
      document.styleSheets[ssMain][cssRules][i].style[cssProp] = cssVal;
      return;
    }
  }
}

Make sure that the rule that you want to modify already exist in the CSS file and are in the correct cascading order, even if they're empty. Otherwise, if a selector doesn't have a rule, you would have to use document.styleSheets[index].insertRule() for which you would have to specify where in the list of rules should the rule be inserted.

changeCSSStyle('.warning', 'color', 'red');
changeCSSStyle('td.special', 'fontSize', '14px');
查看更多
登录 后发表回答