通常我有一个CSS文件,它有以下规则:
#my-window {
position: fixed;
z-index: 102;
display:none;
top:50%;
left:50%;
}
Run Code Online (Sandbox Code Playgroud)
如何通过在运行时操作期间将CSS信息添加到正文或类似的东西来避免创建这样的静态CSS文件?(仅使用jQuery)
我想用jQuery定义一次,然后多次使用它; 这就是为什么我不想每次都将它添加到特定的DOM元素.
我知道简单的功能(css("attr1", "value");
),但是如何创建完整的可重用CSS规则?
小智 260
您可以创建样式元素并将其插入DOM
$("<style type='text/css'> .redbold{ color:#f00; font-weight:bold;} </style>").appendTo("head");
$("<div/>").addClass("redbold").text("SOME NEW TEXT").appendTo("body");
Run Code Online (Sandbox Code Playgroud)
在Opera10 FF3.5 iE8 iE6上测试
Sha*_*ina 107
只是
$("<style>")
.prop("type", "text/css")
.html("\
#my-window {\
position: fixed;\
z-index: 102;\
display:none;\
top:50%;\
left:50%;\
}")
.appendTo("head");
Run Code Online (Sandbox Code Playgroud)
注意到背斜线?它们用于连接新行上的字符串.离开它们会产生错误.
Yuv*_*rmi 18
你可以将css应用于一个对象.所以你可以在你的javascript中定义你的对象,如下所示:
var my_css_class = { backgroundColor : 'blue', color : '#fff' };
Run Code Online (Sandbox Code Playgroud)
然后只需将其应用于您想要的所有元素
$("#myelement").css(my_css_class);
Run Code Online (Sandbox Code Playgroud)
所以它是可重用的.你会这样做的目的是什么?
Sea*_*ean 12
根据dottoro的说法,如果你不需要支持IE <9,你可以使用insertRule.那里还有一些跨浏览器代码.
document.styleSheets[0].insertRule('#my-window {\
position: fixed;\
z-index: 102;\
display:none;\
top:50%;\
left:50%;\
}', 0)
Run Code Online (Sandbox Code Playgroud)
这是一个jquery插件,允许你注入CSS:
https://github.com/kajic/jquery-injectCSS
例:
$.injectCSS({
"#my-window": {
"position": "fixed",
"z-index": 102,
"display": "none",
"top": "50%",
"left": "50%"
}
});
Run Code Online (Sandbox Code Playgroud)
与其他一些答案相比,这并不是什么新东西,因为它使用了这里和这里描述的概念,但我想使用JSON样式的声明:
function addCssRule(rule, css) {
css = JSON.stringify(css).replace(/"/g, "").replace(/,/g, ";");
$("<style>").prop("type", "text/css").html(rule + css).appendTo("head");
}
Run Code Online (Sandbox Code Playgroud)
用法:
addCssRule(".friend a, .parent a", {
color: "green",
"font-size": "20px"
});
Run Code Online (Sandbox Code Playgroud)
我不确定它是否涵盖了CSS的所有功能,但到目前为止它对我有用.如果没有,请将其视为满足您自身需求的起点.:)
如果您不想将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);
});
Run Code Online (Sandbox Code Playgroud)
如果您创建需要自定义CSS的jQuery小部件(例如,为特定小部件扩展现有的jQueryUI CSS框架),则添加自定义规则非常有用。该解决方案基于Taras的答案(上面的第一个答案)。
假设您的HTML标记具有一个ID为“ addrule”的按钮和一个ID为“ target”的div,其中包含一些文本:
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");
}
Run Code Online (Sandbox Code Playgroud)
这种方法的优点是您可以在代码中重用可变的cssrules来随意添加或减少规则。如果cssrules嵌入在诸如jQuery小部件之类的持久对象中,则可以使用一个持久局部变量。
请注意,jQuery().css()
不会更改样式表规则,它只是更改每个匹配元素的样式.
相反,这是我写的一个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);
}
}
Run Code Online (Sandbox Code Playgroud)
好处:
<head>
创建DOM元素之前在脚本中计算,因此在第一次呈现文档之前,避免视觉上令人讨厌的渲染,然后计算,然后重新渲染.使用jQuery,您必须等待创建DOM元素,然后重新设置样式并重新呈现它们.jQuery(newElement).css()
注意事项:
s.cssRules
定义,因此它们会回归到s.rules
具有某些特性的地方,例如与逗号分隔的选择器相关的奇怪/错误行为,例如"body, p"
.如果你避免这些,你可能没有修改旧IE版本,但我还没有测试它."first, second"
即分隔符是逗号后跟空格字符.!important
毫不费力地添加对媒体查询和修饰符的支持.如果您想对此功能进行一些改进,可以在此处找到一些有用的API文档:https: //developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet
在(不寻常的)情况下,您希望能够经常动态更改样式——例如主题构建器应用程序——添加 <style> 标签或调用 CSSStyleSheet.insertRule() 将导致样式表不断增长,这可以提高性能和设计调试含义。
我的方法只允许每个选择器/属性组合有一个规则,清除设置任何规则时的任何现有规则。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;
}
Run Code Online (Sandbox Code Playgroud)
用法:
addStyles('body', {
'background-color': 'black',
color: 'green',
margin: 'auto'
});
clearStyle('body', 'background-color');
addStyle('body', 'color', '#333')
Run Code Online (Sandbox Code Playgroud)
Jor*_*enB -2
也许您可以将样式信息放在 css 文件中的单独类中,例如:
.specificstyle {
position: fixed;
z-index: 102;
display:none;
top:50%;
left:50%;
}
Run Code Online (Sandbox Code Playgroud)
然后在您选择将此类名添加到元素时使用 jQuery?