在运行时使用 jQuery 创建 CSS 规则/类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1212500/
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
Create a CSS rule / class with jQuery at runtime
提问by stephan
Usually I have a CSS file which has the following rule:
通常我有一个 CSS 文件,它具有以下规则:
#my-window {
position: fixed;
z-index: 102;
display:none;
top:50%;
left:50%;
}
How can I avoid creating such a static CSS file by adding the CSS information during runtime actions to the body, or something similar? (only using jQuery)
如何通过在运行时操作期间将 CSS 信息添加到正文或类似内容来避免创建此类静态 CSS 文件?(仅使用 jQuery)
I want to define it once but with jQuery and use it many times later; that's why I do not want to add it each time to the specific DOM elements.
我想定义一次但使用 jQuery 并在以后多次使用它;这就是为什么我不想每次都将它添加到特定的 DOM 元素。
I know the simple features (css("attr1", "value");
), but how can I create a complete reusable CSS rule?
我知道简单的特性 ( css("attr1", "value");
),但我怎样才能创建一个完整的可重用 CSS 规则?
回答by Taras Bulba
You can create style element and insert it into DOM
您可以创建样式元素并将其插入到 DOM 中
$("<style type='text/css'> .redbold{ color:#f00; font-weight:bold;} </style>").appendTo("head");
$("<div/>").addClass("redbold").text("SOME NEW TEXT").appendTo("body");
tested on Opera10 FF3.5 iE8 iE6
在 Opera10 FF3.5 iE8 iE6 上测试
回答by Shadrack B. Orina
Simply
简单地
$("<style>")
.prop("type", "text/css")
.html("\
#my-window {\
position: fixed;\
z-index: 102;\
display:none;\
top:50%;\
left:50%;\
}")
.appendTo("head");
Noticed the back slashes? They are used to join strings that are on new lines. Leaving them out generates an error.
注意到反斜杠了吗?它们用于连接新行上的字符串。将它们排除在外会产生错误。
回答by Yuval Karmi
you can apply css an an object. So you can define your object in your javascript like this:
你可以应用 css 一个对象。所以你可以像这样在你的 javascript 中定义你的对象:
var my_css_class = { backgroundColor : 'blue', color : '#fff' };
And then simply apply it to all the elements you want
然后简单地将它应用到你想要的所有元素
$("#myelement").css(my_css_class);
So it is reusable. What purpose would you do this for though?
所以它是可以重复使用的。你这样做的目的是什么?
回答by Sean
You can use insertRuleif you don't need to support IE < 9, according to dottoro. There's a bit of cross browser code over there as well.
根据dottoro 的说法,如果您不需要支持 IE < 9,则可以使用insertRule。还有一些跨浏览器代码。
document.styleSheets[0].insertRule('#my-window {\
position: fixed;\
z-index: 102;\
display:none;\
top:50%;\
left:50%;\
}', 0)
回答by Robert Kajic
Here is a jquery plugin that allows you to inject CSS:
这是一个允许您注入 CSS 的 jquery 插件:
https://github.com/kajic/jquery-injectCSS
https://github.com/kajic/jquery-injectCSS
Example:
例子:
$.injectCSS({
"#my-window": {
"position": "fixed",
"z-index": 102,
"display": "none",
"top": "50%",
"left": "50%"
}
});
回答by sjngm
This isn't anything new compared to some of the other answers as it uses the concept described hereand here, but I wanted to make use of JSON-style declaration:
与其他一些答案相比,这并不是什么新鲜事,因为它使用了此处和此处描述的概念,但我想使用 JSON 样式的声明:
function addCssRule(rule, css) {
css = JSON.stringify(css).replace(/"/g, "").replace(/,/g, ";");
$("<style>").prop("type", "text/css").html(rule + css).appendTo("head");
}
Usage:
用法:
addCssRule(".friend a, .parent a", {
color: "green",
"font-size": "20px"
});
I'm not sure if it covers all capabilities of CSS, but so far it works for me. If it doesn't, consider it a starting points for your own needs.:)
我不确定它是否涵盖了 CSS 的所有功能,但到目前为止它对我有用。如果没有,请将其视为满足您自己需求的起点。:)
回答by Mike Trpcic
If you don't want to hardcode the CSS into a CSS block/file, you can use jQuery to dynamically add CSS to HTML Elements, ID's, and Classes.
如果您不想将 CSS 硬编码到 CSS 块/文件中,您可以使用 jQuery 将 CSS 动态添加到 HTML 元素、ID 和类。
$(document).ready(function() {
//Build your CSS.
var body_tag_css = {
"background-color": "#ddd",
"font-weight": "",
"color": "#000"
}
//Apply your CSS to the body tag. You can enter any tag here, as
//well as ID's and Classes.
$("body").css(body_tag_css);
});
回答by Craig
Note that jQuery().css()
doesn't change stylesheet rules, it just changes the style of each matched element.
请注意,jQuery().css()
不会更改样式表规则,它只会更改每个匹配元素的样式。
Instead, here's a javascript function I wrote to modify the stylesheet rules themselves.
相反,这是我编写的一个 javascript 函数来修改样式表规则本身。
/**
* Modify an existing stylesheet.
* - sheetId - the id of the <link> or <style> element that defines the stylesheet to be changed
* - selector - the id/class/element part of the rule. e.g. "div", ".sectionTitle", "#chapter2"
* - property - the CSS attribute to be changed. e.g. "border", "font-size"
* - value - the new value for the CSS attribute. e.g. "2px solid blue", "14px"
*/
function changeCSS(sheetId, selector, property, value){
var s = document.getElementById(sheetId).sheet;
var rules = s.cssRules || s.rules;
for(var i = rules.length - 1, found = false; i >= 0 && !found; i--){
var r = rules[i];
if(r.selectorText == selector){
r.style.setProperty(property, value);
found = true;
}
}
if(!found){
s.insertRule(selector + '{' + property + ':' + value + ';}', rules.length);
}
}
Advantages:
好处:
- Styles can be computed in a
<head>
script before the DOM elements are created and therefore prior to the first rendering of the document, avoiding a visually-annoying render, then compute, then re-render. With jQuery, you'd have to wait for the DOM elements to be created, then re-style and re-render them. - Elements that are added dynamically after the restyle will automatically have the new styles applied without an extra call to
jQuery(newElement).css()
- 样式可以在
<head>
创建 DOM 元素之前在脚本中计算,因此在第一次渲染文档之前,避免视觉上烦人的渲染,然后计算,然后重新渲染。使用 jQuery,您必须等待创建 DOM 元素,然后重新设置样式并重新渲染它们。 - 在重新设置样式后动态添加的元素将自动应用新样式,而无需额外调用
jQuery(newElement).css()
Caveats:
注意事项:
- I've used it on Chrome and IE10. I think it might need a little modification to make it work well on older versions of IE. In particular, older versions of IE might not have
s.cssRules
defined, so they will fall back tos.rules
which has some peculiarities, such as odd/buggy behavior related to comma-delimited selectors, like"body, p"
. If you avoid those, you might be ok in older IE versions without modification, but I haven't tested it yet. - Currently selectors need to match exactly: use lower case, and be careful with comma-delimited lists; the order needs to match and they should be in the format
"first, second"
i.e the delimiter is a comma followed by a space character. - One could probably spend some additional time on it trying to detect and intelligently handle overlapping selectors, such as those in comma-delimited lists.
- One could also add support for media queries and the
!important
modifier without too much trouble.
- 我已经在 Chrome 和 IE10 上使用过它。我认为它可能需要进行一些修改才能使其在旧版本的 IE 上运行良好。特别是,旧版本的 IE 可能没有
s.cssRules
定义,因此它们会回退到s.rules
具有一些特殊性的地方,例如与逗号分隔的选择器相关的奇怪/错误行为,例如"body, p"
. 如果您避免使用这些,则无需修改即可在较旧的 IE 版本中使用,但我尚未对其进行测试。 - 目前选择器需要精确匹配:使用小写,并小心使用逗号分隔的列表;订单需要匹配,它们应该采用以下格式,
"first, second"
即分隔符是逗号后跟一个空格字符。 - 人们可能会花一些额外的时间来尝试检测和智能处理重叠的选择器,例如逗号分隔列表中的选择器。
- 还可以添加对媒体查询和
!important
修饰符的支持,不会有太多麻烦。
If you feel like making some improvements to this function, you'll find some useful API docs here: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet
如果您想对此功能进行一些改进,您可以在这里找到一些有用的 API 文档:https: //developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet
回答by fbloggs
Adding custom rules is useful if you create a jQuery widget that requires custom CSS (such as extending the existing jQueryUI CSS framework for your particular widget). This solution builds on Taras's answer (the first one above).
如果您创建需要自定义 CSS 的 jQuery 小部件(例如为您的特定小部件扩展现有的 jQueryUI CSS 框架),则添加自定义规则非常有用。该解决方案建立在 Taras 的答案(上面的第一个)之上。
Assuming your HTML markup has a button with an id of "addrule" and a div with an id of "target" containing some text:
假设您的 HTML 标记有一个 id 为“addrule”的按钮和一个包含一些文本的 id 为“target”的 div:
jQuery code:
jQuery代码:
$( "#addrule" ).click(function () { addcssrule($("#target")); });
function addcssrule(target)
{
var cssrules = $("<style type='text/css'> </style>").appendTo("head");
cssrules.append(".redbold{ color:#f00; font-weight:bold;}");
cssrules.append(".newfont {font-family: arial;}");
target.addClass("redbold newfont");
}
The advantage of this approach is that you can reuse variable cssrules in your code to add or subtract rules at will. If cssrules is embedded in a persistent object such as a jQuery widget you have a persistent local variable to work with.
这种方法的优点是你可以在代码中重用变量 cssrules 来随意添加或减去规则。如果 cssrules 被嵌入到一个持久对象中,比如一个 jQuery 小部件,那么你有一个持久的局部变量可以使用。
回答by Jason Boyd
In (unusual) cases where you want to be able to dynamically change styles often -- e.g. a theme builder app -- adding <style> tags or calling CSSStyleSheet.insertRule() will result in a growing stylesheet, which can have performance and design debugging implications.
在(不寻常的)情况下,您希望能够经常动态更改样式——例如主题构建器应用程序——添加 <style> 标签或调用 CSSStyleSheet.insertRule() 将导致样式表不断增长,这可以提高性能和设计调试含义。
My approach only allows a single rule per selector/property combo, clearing any existing on setting any rule. The API is simple and flexible:
我的方法只允许每个选择器/属性组合有一个规则,清除设置任何规则时的任何现有规则。API 简单灵活:
function addStyle(selector, rulename, value) {
var stylesheet = getAppStylesheet();
var cssRules = stylesheet.cssRules || stylesheet.rules;
var rule = stylesheet.insertRule(selector + ' { ' + rulename + ':' + value + ';}', cssRules.length);
}
function clearStyle(selector, rulename) {
var stylesheet = getAppStylesheet();
var cssRules = stylesheet.cssRules || stylesheet.rules;
for (var i=0; i<cssRules.length; i++) {
var rule = cssRules[i];
if (rule.selectorText == selector && rule.style[0] == rulename) {
stylesheet.deleteRule(i);
break;
}
}
}
function addStyles(selector, rules) {
var stylesheet = getAppStylesheet();
var cssRules = stylesheet.cssRules || stylesheet.rules;
for (var prop in rules) {
addStyle(selector, prop, rules[prop]);
}
}
function getAppStylesheet() {
var stylesheet = document.getElementById('my-styles');
if (!stylesheet) {
stylesheet = $('<style id="my-styles">').appendTo('head')[0];
}
stylesheet = stylesheet.sheet;
return stylesheet;
}
Usage:
用法:
addStyles('body', {
'background-color': 'black',
color: 'green',
margin: 'auto'
});
clearStyle('body', 'background-color');
addStyle('body', 'color', '#333')