Javascript 如何将自己的行添加到CSS片段中

Javascript 如何将自己的行添加到CSS片段中,javascript,css,Javascript,Css,如何将新规则添加到此CSS样式表 .tag { background: #333333; border-radius: 3px; color: #ffffff; font: 10px "Gibson-Regular", sans-serif; letter-spacing: 1px; margin-right: 1px; padding: 2px 3px 2px 4px; position: relative; top: -1px; text-transf

如何将新规则添加到此CSS样式表

.tag {
  background: #333333;
  border-radius: 3px;
  color: #ffffff;
  font: 10px "Gibson-Regular", sans-serif;
  letter-spacing: 1px;
  margin-right: 1px;
  padding: 2px 3px 2px 4px;
  position: relative;
  top: -1px;
  text-transform: uppercase; 
}

.tag a {
  color: #ffffff;
  text-decoration: none !important; 
}

// already in the code
.tag.yolo {
  background-color: #0066CC; 
}

// I want this to be added
.tag.yolo {
  background-color: #0066CC; 
}
我更喜欢只使用Javascript来实现这一点

.tag.yolo {
  background-color: #0066CC; 
}

使用上述问题中引用的API,您可以这样做:

var all = document.styleSheets,
    s = all[all.length - 1],
    l = s.cssRules.length;

if (s.insertRule) {
    s.insertRule('.tag.yolo { background-color: #0066CC; }', l);
} else {
    //IE
    s.addRule('.tag.yolo { background-color: #0066CC; }', -1);
}​
或者这种方法:

var css = document.createElement("style");
css.type = "text/css";
css.innerHTML = ".tag.yolo { background-color: #0066CC; }";
document.body.appendChild(css);

我只是看着那个。。。在我看来,它似乎只创建了一个内联对象。。。我想创建.tag.yolo{而不是添加颜色或管理权重。@user3289948不,这是最基本的内容。如果您对链接答案中的命令感到困惑,请尝试阅读API。只是测试了一下,没有问题work@user3289948尝试另一种方法