Javascript设置CSS:样式之后

你能用Javascript设置:使用CSS的样式吗?

所以我们说:

$("#foo li:after").css("left","100px"); 

 var addRule = (function(style){ var sheet = document.head.appendChild(style).sheet; return function(selector, css){ var propText = Object.keys(css).map(function(p){ return p+":"+css[p] }).join(";"); sheet.insertRule(selector + "{" + propText + "}", sheet.cssRules.length); } })(document.createElement("style")); addRule("p:before", { display: "block", width: "100px", height: "100px", background: "red", "border-radius": "50%", content: "''" }); 

最小的实现。 您很可能希望跟踪添加的规则,以便删除它们。 sheet.insertRule返回新规则的索引,您可以使用该索引获取对其的引用以进行编辑或删除。

编辑:为方便起见,添加了将对象转换为css属性字符串的基本function。