jQuery CSS - 写入<style> -tag

Pet*_*ter 32 css jquery stylesheet

我想改变background-colorbody我的HTML文档.我的问题是jQuery将样式添加到body标记,但我想更改style标记中的值.这可能使用jQuery吗?

例如,代码

    <style title="css_style" type="text/css">
    body {
      background-color:#dc2e2e;     /* <- CHANGE THIS */
      color:#000000;
      font-family:Tahoma, Verdana;
      font-size:11px;
      margin:0px;
      padding:0px;
      background-image: url(http://abc.de/image.jpg);
    }
    </style>

    ...

    <body>
       // ....
    </body>
Run Code Online (Sandbox Code Playgroud)

jQuery的

$('body').css('background-color','#ff0000');
Run Code Online (Sandbox Code Playgroud)

结果

<body style="background-color:#ff0000;">
   // ....
</body>
Run Code Online (Sandbox Code Playgroud)

Jör*_*rer 119

虽然不更改现有的样式元素,但这可以作为创建新元素的跨浏览器方式:

$( "<style>body { background: black; }</style>" ).appendTo( "head" )
Run Code Online (Sandbox Code Playgroud)

通过级联,它将覆盖现有的样式,这应该可以解决问题.

  • 最好,最干净的答案.在Chrome和IE8中进行了测试(在IE7模式下).我唯一的变化是appendTo("head"),而不是"body",因为样式标签只应包含在头部中(当然,除非HTML5"scoped"属性包含在样式标记中,但由于这是目前不支持任何浏览器,我们可以忽略此选项). (6认同)

Dr.*_*lle 30

这是操作样式表的具体方法,

DOM:insertRule()
Microsoft:addRule()

我刚刚为jQuery创建了一个方法(也许其他人已经做了,我不知道)

(
function( $ )
{
  $.style={
          insertRule:function(selector,rules,contxt)
          {
            var context=contxt||document,stylesheet;

            if(typeof context.styleSheets=='object')
            {
              if(context.styleSheets.length)
              {
                stylesheet=context.styleSheets[context.styleSheets.length-1];
              }
              if(context.styleSheets.length)
              {
                if(context.createStyleSheet)
                {
                  stylesheet=context.createStyleSheet();
                }
                else
                {
                  context.getElementsByTagName('head')[0].appendChild(context.createElement('style'));
                  stylesheet=context.styleSheets[context.styleSheets.length-1];
                }
              }
              if(stylesheet.addRule)
              {
                for(var i=0;i<selector.length;++i)
                {
                  stylesheet.addRule(selector[i],rules);
                }
              }
              else
              {
                stylesheet.insertRule(selector.join(',') + '{' + rules + '}', stylesheet.cssRules.length);  
              }
            }
          }
        };
  }
)( jQuery );
Run Code Online (Sandbox Code Playgroud)

用法示例:

$.style.insertRule(['p','h1'], 'color:red;')
$.style.insertRule(['p'],      'text-decoration:line-through;')
$.style.insertRule(['div p'],  'text-decoration:none;color:blue')
Run Code Online (Sandbox Code Playgroud)

第二个论点应该是明确的,规则.作为可选的第3个参数,可以提供context-document.
第一个参数是选择器作为数组元素.
请注意,您不必使用逗号分隔的不同选择器,因为MSIE仅接受"单个上下文选择器"作为addRule()的参数

看看小提琴:http://jsfiddle.net/doktormolle/ubDDd/

  • 有没有办法在样式标签中操纵现有规则? (2认同)

Sha*_*aoz 8

jQuery总是在标签本身添加它的CSS.

我认为你应该使用append()具有新体型规则的函数.

像这样:

var newRule = "body{ /*your CSS rule here...*/ }";
$("style").append(newRule);
Run Code Online (Sandbox Code Playgroud)

要么

$("body").css({ /*CSS rule...*/ });
Run Code Online (Sandbox Code Playgroud)

我希望这就是你的意思......


Asi*_*Rex 5

也许将所有现有规则复制到字符串、添加内容或修改其中的内容、删除现有标签并替换修改后的内容更容易,如下所示:

//Initialize variable
var cssRules = '';
//Copy existing rules
for (var i = 0; i < document.styleSheets[0].cssRules.length; i++) {
    cssRules += document.styleSheets[0].cssRules[i].cssText;
}
//Delete existing node
$('style').remove();

// .... Add stuff to cssRules

//Append new nodes
$('<style>' + cssRules + '</style>').appendTo('head');
Run Code Online (Sandbox Code Playgroud)