jQuery CSS -写入-tag

时间:2022-08-30 09:43:59

I want to change the background-color of the body of my HTML document. My problem is that jQuery adds the style to the body tag, but I want to change the value in the style tag. Is this possible using jQuery?

我想更改HTML文档主体的背景颜色。我的问题是,jQuery将样式添加到body标签中,但我想要更改样式标记中的值。使用jQuery可以实现这一点吗?

Example-Code

示例代码

    <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>

jQuery

jQuery

$('body').css('background-color','#ff0000');

Result

结果

<body style="background-color:#ff0000;">
   // ....
</body>

7 个解决方案

#1


30  

The are specific methods for manipulating stylesheets,

这些是操作样式表的特定方法,

DOM: insertRule()
Microsoft: addRule()

DOM:insertRule()微软:addRule()

I just made a method for jQuery(maybe somebody else already did, I don't know)

我刚为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 );

Example usage:

使用示例:

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

the second argument should be clear, the rules. As optional 3rd argument the context-document can be supplied.
The first argument are the selectors as array-elements.
Note that you dont have to use there different selector separated by comma, as MSIE only accepts "Single contextual selectors" as argument for addRule()

第二个论点应该是明确的,规则。作为可选的第三个参数,可以提供上下文文档。第一个参数是选择器作为数组元素。注意,您不必使用用逗号分隔的不同选择器,因为MSIE只接受“单个上下文选择器”作为addRule()的参数

Check out the fiddle: http://jsfiddle.net/doktormolle/ubDDd/

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

#2


111  

While not changing an existing style element, this works as a cross-browser way to create a new one:

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

$( "<style>body { background: black; }</style>" ).appendTo( "head" )

By cascading, it'll override existing styles, which should do the trick.

通过级联,它将覆盖现有的样式,这应该可以达到目的。

#3


7  

jQuery always adds its CSS in the tag itself.

jQuery总是在标签中添加它的CSS。

I think you should use the append() function with a new body style rule.

我认为您应该使用append()函数来使用新的body样式规则。

Like this:

是这样的:

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

or

$("body").css({ /*CSS rule...*/ });

I hope this is what you meant...

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

#4


3  

I was able to modify the section by adding to it's html.

我可以通过添加到它的html来修改这个部分。

var styleText = $('style').html();
styleText += '\n' + '#TabName div ul li a {border-top-left-radius:5px;}';
$('style').html(styleText);

#5


2  

You can change your body class but you cannot change your style tag:

您可以更改body类,但不能更改样式标签:

HTML:

<style title="css_style" type="text/css">
.highlight
{
    background-color:#ff0000;   
}
</style>

JavaScript:

$('body').toggleClass(".highlight");

#6


0  

Perhaps it's easier to copy all the existing rules to a string, add your stuff or modify what's in there, delete the existing tag and replacing it modified, like so:

也许将所有现有的规则复制到字符串中、添加内容或修改其中的内容、删除现有的标记并替换为已修改的标记会更容易一些,比如:

//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');

#7


0  

None of the existing answers mention jqueryEl.text, so here it is:

现有的答案中没有一个提到jqueryEl。文本,这里是

$("<style/>").text(css).appendTo(document.head);

#1


30  

The are specific methods for manipulating stylesheets,

这些是操作样式表的特定方法,

DOM: insertRule()
Microsoft: addRule()

DOM:insertRule()微软:addRule()

I just made a method for jQuery(maybe somebody else already did, I don't know)

我刚为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 );

Example usage:

使用示例:

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

the second argument should be clear, the rules. As optional 3rd argument the context-document can be supplied.
The first argument are the selectors as array-elements.
Note that you dont have to use there different selector separated by comma, as MSIE only accepts "Single contextual selectors" as argument for addRule()

第二个论点应该是明确的,规则。作为可选的第三个参数,可以提供上下文文档。第一个参数是选择器作为数组元素。注意,您不必使用用逗号分隔的不同选择器,因为MSIE只接受“单个上下文选择器”作为addRule()的参数

Check out the fiddle: http://jsfiddle.net/doktormolle/ubDDd/

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

#2


111  

While not changing an existing style element, this works as a cross-browser way to create a new one:

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

$( "<style>body { background: black; }</style>" ).appendTo( "head" )

By cascading, it'll override existing styles, which should do the trick.

通过级联,它将覆盖现有的样式,这应该可以达到目的。

#3


7  

jQuery always adds its CSS in the tag itself.

jQuery总是在标签中添加它的CSS。

I think you should use the append() function with a new body style rule.

我认为您应该使用append()函数来使用新的body样式规则。

Like this:

是这样的:

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

or

$("body").css({ /*CSS rule...*/ });

I hope this is what you meant...

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

#4


3  

I was able to modify the section by adding to it's html.

我可以通过添加到它的html来修改这个部分。

var styleText = $('style').html();
styleText += '\n' + '#TabName div ul li a {border-top-left-radius:5px;}';
$('style').html(styleText);

#5


2  

You can change your body class but you cannot change your style tag:

您可以更改body类,但不能更改样式标签:

HTML:

<style title="css_style" type="text/css">
.highlight
{
    background-color:#ff0000;   
}
</style>

JavaScript:

$('body').toggleClass(".highlight");

#6


0  

Perhaps it's easier to copy all the existing rules to a string, add your stuff or modify what's in there, delete the existing tag and replacing it modified, like so:

也许将所有现有的规则复制到字符串中、添加内容或修改其中的内容、删除现有的标记并替换为已修改的标记会更容易一些,比如:

//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');

#7


0  

None of the existing answers mention jqueryEl.text, so here it is:

现有的答案中没有一个提到jqueryEl。文本,这里是

$("<style/>").text(css).appendTo(document.head);