使用 jQuery 更改 CSS 类属性 [英] Change CSS class properties with jQuery
问题描述
有没有办法使用 jQuery 更改 CSS 类的属性,而不是元素属性?
Is there a way to change the properties of a CSS class, not the element properties, using jQuery?
这是一个实际的例子:
我有一个 red
.red {background: red;}
我想更改 class red
背景属性,而不是分配了 class red
背景的元素.
I want to change class red
background property, not elements that have class red
background assigned.
如果我使用 jQuery .css() 方法:
If I do it with jQuery .css() method:
$('.red').css('background','green');
它会影响现在具有 red
类的元素.到这里一切都很好.但是,如果我进行 Ajax 调用,并插入更多带有 red
类的 div,这些 div 将不会有绿色背景,它们将具有初始 red
背景.
it will affect the elements that right now have class red
. Up to here everything is fine.
But if I make an Ajax call, and insert more divs with red
class, those won't have a green background, they will have the initial red
background.
我可以再次调用 jQuery .css() 方法.但我想知道是否有办法改变类本身.请考虑这只是一个基本示例.
I could call jQuery .css() method again. But I would like to know if there is a way to change the class itself. Please 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);
}
}
上面的例子复制自:
$("head").append('<style type="text/css"></style>');
var newStyleElement = $("head").children(':last');
newStyleElement.html('.red{background:green;}');
示例代码复制自 this JSFiddle fiddle 最初由 Alvaro 在他们的评论中.
The example code is copied from this JSFiddle fiddle originally referenced by Alvaro in their comment.
这篇关于使用 jQuery 更改 CSS 类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!