Javascript 设置 CSS :after 样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7330355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript set CSS :after styles
提问by Harry
Can you set the :after styles of css with Javascript?
你能用 Javascript 设置 :after css 样式吗?
So lets say:
所以让我们说:
$("#foo li:after").css("left","100px");
回答by
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: "''"
});
A minimal implementation. You most likely would want to keep track of the rules you add so you can remove them. sheet.insertRule
returns the index of the new rule which you can use to get a reference to it for editing or removal.
一个最小的实现。您很可能希望跟踪您添加的规则,以便您可以删除它们。sheet.insertRule
返回新规则的索引,您可以使用它来获取对它的引用以进行编辑或删除。
Edit: added basic functionality to convert an object into a css property string for convenience.
编辑:为方便起见,添加了将对象转换为 css 属性字符串的基本功能。