简体   繁体   English

更改CSS样式表的选择器的属性

[英]Change a CSS stylesheet's selectors' properties

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. 我不想遍历匹配选择器的元素并直接应用CSS或向元素添加修饰符类。

  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. 确保您要修改的规则已经存在于CSS文件中,并且以正确的级联顺序排列,即使它们为空。 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. 否则,如果选择器没有规则,则必须使用document.styleSheets[index].insertRule() ,必须为其指定规则列表中应插入规则的位置。

changeCSSStyle('.warning', 'color', 'red');
changeCSSStyle('td.special', 'fontSize', '14px');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM