在运行时使用jQuery创建CSS规则/类

ste*_*han 183 css jquery

通常我有一个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上测试

  • 在IE9中,页面中只有31种样式 - http://blogs.msdn.com/b/ieinternals/archive/2011/05/14/internet-explorer-stylesheet-rule-selector-import-sheet-limit-maximum的.aspx (6认同)

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)

注意到背斜线?它们用于连接新行上的字符串.离开它们会产生错误.

  • 这个.应该是接受的答案.它实际上回答了这个问题. (6认同)
  • 我同意@JohannesPille,这才是真正的答案! (2认同)
  • 相当有效和直截了当.将新规则注入标题后,您可以在页面的任何位置检索它,包括PHP. (2认同)

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)

所以它是可重用的.你会这样做的目的是什么?

  • 我会说这是一个CSS规则而*不是一个CSS类. (21认同)
  • 这个答案有误导性.提问者想要在运行时创建CSS规则,而不是将特定元素的样式设置为常量(可重用)CSS声明. (16认同)
  • 这不是他们要求的,但它是正确的解决方案:)用额外的<style>元素填充dom有一些讨厌的代码味道 (4认同)
  • 如何在需要时删除这些规则,这可以通过其他解决方案实现...... (3认同)

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)


Rob*_*jic 9

这是一个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)


sjn*_*ngm 9

与其他一些答案相比,这并不是什么新东西,因为它使用了这里这里描述的概念,但我想使用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的所有功能,但到目前为止它对我有用.如果没有,请将其视为满足您自身需求的起点.:)


Mik*_*cic 7

如果您不想将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规则,而不是将特定元素的样式设置为常量CSS声明. (5认同)
  • @MikeTrpcic问题是还有其他人在搜索这个解决方案 - 将css规则添加到页面 - 而你的答案并没有解决这个问题. (2认同)

fbl*_*ggs 5

如果您创建需要自定义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小部件之类的持久对象中,则可以使用一个持久局部变量。


Cra*_*aig 5

请注意,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元素,然后重新设置样式并重新呈现它们.
  • 在restyle之后动态添加的元素将自动应用新样式而无需额外调用 jQuery(newElement).css()

注意事项:

  • 我在Chrome和IE10上使用过它.我认为可能需要稍加修改才能使其在旧版本的IE上运行良好.特别是,IE的旧版本可能没有s.cssRules定义,因此它们会回归到s.rules具有某些特性的地方,例如与逗号分隔的选择器相关的奇怪/错误行为,例如"body, p".如果你避免这些,你可能没有修改旧IE版本,但我还没有测试它.
  • 目前选择器需要完全匹配:使用小写,并注意以逗号分隔的列表; 订单需要匹配,它们应该是格式,"first, second"即分隔符是逗号后跟空格字符.
  • 人们可能会花费额外的时间来尝试检测并智能地处理重叠选择器,例如逗号分隔列表中的选择器.
  • 人们还可以!important毫不费力地添加对媒体查询和修饰符的支持.

如果您想对此功能进行一些改进,可以在此处找到一些有用的API文档:https: //developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet


Jas*_*oyd 5

在(不寻常的)情况下,您希望能够经常动态更改样式——例如主题构建器应用程序——添加 <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?