使用jQuery更改Css类属性 [英] Change Css class properties with jQuery
问题描述
有一种方法可以更改CSS类属性,而不是元素属性。
Is there a way to change a CSS class properties, not the element properties.
这是一个实际的例子:
我有一个div 'red'
Here is a practical example: I have a div with class 'red'
.red{background:red;}
我想改变类的'red'背景属性,而不是赋予类'red'后台的元素。
I want to change class 'red' background property, not elements that have class 'red' background assigned.
如果我使用简单的jquery:
If I do it with simple jquery:
$('.red').css('background','green');
它会影响实际上有'red'类的元素。到这里是罚款。
但是如果我进行Ajax调用,并且引入更多的带'red'类的div,那些将没有绿色背景,他们将有初始的'红色'背景。
it will affect the elements that actually have class 'red'. Up to here is fine. But if I make an Ajax call, and introduce more divs with 'red' class, those won't have a green background, they will have the initial 'red' background.
当然我可以再次调用简单的jquery。但我想知道是否有一种方法来改变类本身(用jquery)。 (考虑这只是一个基本的例子)。
Of course I could call the simple jquery again. But I would like to know if there is a way to change the class itself (with jquery). (Consider this is just a basic example).
推荐答案
不能使用jQuery直接改变CSS属性。
You can't change CSS properties directly with jQuery. But you can achieve the same effect in at least two ways.
function updateStyleSheet(filename) {
newstylesheet = "style_" + filename + ".css";
if ($("#dynamic_css").length == 0) {
$("head").append("<link>")
css = $("head").children(":last");
css.attr({
id: "dynamic_css",
rel: "stylesheet",
type: "text/css",
href: newstylesheet
});
} else {
$("#dynamic_css").attr("href",newstylesheet);
}
}
上述示例复制自:
- How To Switch CSS Files On-The-Fly Using jQuery
$("head").append('<style type="text/css"></style>');
var newStyleElement = $("head").children(':last');
newStyleElement.html('.red{background:green;}');
示例代码从 this JSFiddle fiddle 最初由Alvaro引用在他们的评论< a>。
The example code is copied from this JSFiddle fiddle originally referenced by Alvaro in their comment.
这篇关于使用jQuery更改Css类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!