有没有办法使用jQuery更改CSS类的属性,而不是元素属性?

This is a practical example:

我有一个第red班的div

.red {background: red;}

我想更改类red背景属性,而不是指定了类red背景的元素.

如果我使用jQuery .css() method执行此操作:

$('.red').css('background','green');

它会影响到现在red级的元素.到目前为止一切都很好.

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.

推荐答案

You can't change CSS properties directly with jQuery. But you can achieve the same effect in at least two ways.

从文件中动态加载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);
    }
}

The example above is copied from:

动态添加样式元素

$("head").append('<style type="text/css"></style>');
var newStyleElement = $("head").children(':last');
newStyleElement.html('.red{background:green;}');

示例代码是从最初由Alvaro in their comment引用的this JSFiddle fiddle复制而来的.

Jquery相关问答推荐

当一个很长的活动增加标题时,满历js每周都会出现.这是一种让标题只出现一次的方法吗?

如何定位 prism.js 脚本中包含的代码?

为什么 .join() 不能与函数参数一起使用?

jQuery:使用变量作为 Select 器

如何用 javascript/jquery 替换 url 参数?

输入类型=文件的jQuery更改方法

jQuery UI 自动完成宽度未正确设置

jQuery UI 对话框 - 关闭后不打开

试图检测浏览器关闭事件

如何使用 jquery 更改 onclick 事件?

使用 时如何从 select2 中获取选定文本

jquery变量语法

未捕获的 TypeError:data.push 不是函数

如何将数组传递给 jQuery .data() 属性

jQuery Select 器中前导冒号的目的是什么?

jQuery:如何从 $.ajax.error 方法中获取 HTTP 状态代码?

jQuery 按值 Select 选项元素

如何在 Bootstrap 中创建切换按钮

通过 :not 在 jQuery Select 器中隐藏除 $(this) 之外的所有内容

粘性侧边栏:向下滚动时固定在底部,向上滚动时固定在顶部