有没有办法使用 jQuery 更改 CSS 类的属性,而不是元素属性?
这是一个实际的例子:
我有一个类为red
的div
.red {background: red;}
我想更改类 red
背景属性,而不是已分配 red
类背景的元素。
如果我使用 jQuery .css() method :
$('.red').css('background','green');
它将影响现在具有类 red
的元素。到这里一切都很好。
但是如果我进行 Ajax 调用,并插入更多带有 red
类的 div,它们将不会有绿色背景,它们将有初始的 red
背景。
我可以调用 jQuery .css() method再次。但我想知道是否有办法改变类(class)本身。请考虑这只是一个基本示例。
最佳答案
您不能直接使用 jQuery 更改 CSS 属性。但至少可以通过两种方式达到相同的效果。
从文件中动态加载 CSS
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 引用 in their comment .
关于jquery - 使用 jQuery 更改 CSS 类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11474430/