问题描述
有没有办法来改变一个CSS类的属性,而不是元素属性。
Is there a way to change a CSS class properties, not the element properties.
下面是一个实际的例子:我有类红色
Here is a practical example:I have a div with class 'red'
.red{background: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');
它会影响实际上已经下课'红'的元素。截至这边独好。但是,如果我做一个Ajax调用,并推出更多的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);
}
}
上面的例子是从复制:
The example above is copied from:
$("head").append('<style type="text/css"></style>');
var newStyleElement = $("head").children(':last');
newStyleElement.html('.red{background:green;}');
The example code is copied from this JSFiddle fiddle originally referenced by Alvaro in their comment.
这篇关于更改CSS类的属性与jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!