答案应该是
Jain。你不能通过伪选择器选择元素,但可以使用
insertRule
在样式表中添加新规则。
我为您制作了一个可以解决问题的东西:
var addRule = function(sheet, selector, styles) {
if (sheet.insertRule) return sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
if (sheet.addRule) return sheet.addRule(selector, styles);
};
addRule(document.styleSheets[0], "body:before", "content: 'foo'");
http://fiddle.jshell.net/MDyxg/1/
为了变得超级酷(并且回答问题真的),我将其再次推出,并将其封装在一个jQuery插件中(不过,仍然不需要jquery!):
(function ($) {
window.addRule = function (selector, styles, sheet) {
styles = (function (styles) {
if (typeof styles === "string") return styles;
var clone = "";
for (var p in styles) {
if (styles.hasOwnProperty(p)) {
var val = styles[p];
p = p.replace(/([A-Z])/g, "-$1").toLowerCase();
clone += p + ":" + (p === "content" ? '"' + val + '"' : val) + "; ";
}
}
return clone;
}(styles));
sheet = sheet || document.styleSheets[document.styleSheets.length - 1];
if (sheet.insertRule) sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
else if (sheet.addRule) sheet.addRule(selector, styles);
return this;
};
if ($) $.fn.addRule = function (styles, sheet) {
addRule(this.selector, styles, sheet);
return this;
};
}(window.jQuery));
使用方法非常简单:
$("body:after").addRule({
content: "foo",
color: "red",
fontSize: "32px"
});
addRule("body:after", {
content: "foo",
color: "red",
fontSize: "32px"
});
https://gist.github.com/yckart/5563717