如何使用 jQuery 更改 css 类规则?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/622122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:28:18  来源:igfitidea点击:

How can I change the css class rules using jQuery?

jquerycss

提问by Yasir

Can any one help me please, I have two sections of my question.

任何人都可以帮助我吗,我的问题有两个部分。

  1. What I want to do is changing css class rules using jQuery on the fly.

    .classname{color:red; font-size:14px;}

    In example above I have a class named .classnamenow using jQuery I want to change the font size only not color with in .classnamenot by adding css inline.

  2. I want to create and save .classnamechange to a file remember there will be complete stylesheet or no of classnames that will be save in file.

  1. 我想要做的是使用 jQuery 即时更改 css 类规则。

    .classname{color:red; font-size:14px;}

    在上面的示例中,我有一个.classname使用 jQuery命名的类,我只想.classname通过添加 css 内联来更改字体大小而不是颜色。

  2. 我想创建并保存.classname对文件的更改,记住会有完整的样式表或没有将保存在文件中的类名。

How I can do this the easiest and better way?

我怎样才能以最简单和更好的方式做到这一点?

Thanks!

谢谢!

回答by Ionu? G. Stan

As far as I know there's no jQuery way to do this. There might be some jQuery plugin for this but I don't know.

据我所知,没有 jQuery 方法可以做到这一点。可能有一些 jQuery 插件,但我不知道。

Basically, what you're trying to achieve in your first question is possible using the styleSheetsproperty of the documentobject. It's a little bit more complicated than that as you need to walk to a rather deep object chain, but nevertheless works in all major browsers including Internet Explorer 6. Below is a proof of concept. The CSS is inside a STYLE tag, but works with external CSS just as well. I'll let you do the abstractions.

基本上,您可以使用对象的styleSheets属性在第一个问题中实现document。它比这稍微复杂一些,因为您需要访问一个相当深的对象链,但仍然适用于包括 Internet Explorer 6 在内的所有主要浏览器。下面是一个概念证明。CSS 位于 STYLE 标签内,但也适用于外部 CSS。我会让你做抽象。

Proof of Concept

概念证明

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html>
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta http-equiv="imagetoolbar" content="false">
<meta http-equiv="imagetoolbar" content="no">
<style type="text/css">
.classname {
 color: red;
 font-size: 14px;
}
</style>
<script type="text/javascript">
window.onload = function() {
    document.getElementById("button").onclick = function() {
        var ss = document.styleSheets;

        for (var i=0; i<ss.length; i++) {
            var rules = ss[i].cssRules || ss[i].rules;

            for (var j=0; j<rules.length; j++) {
                if (rules[j].selectorText === ".classname") {
                    rules[j].style.color = "green";
                }
            }
        }
    };
}
</script>
</head>
<body>

<h1 class="classname">Some red text</h1>

<button id="button">Make text green</button>

</body>
</html>

For your second question, I don't have time to write a solution but it would involve reading the CSS declarations just as above and use the cssTextproperty of a CssRule object in order to build a string which will eventually be sent to the server using a Ajax POST request. The server side is your business.

对于您的第二个问题,我没有时间编写解决方案,但它会涉及到如上所述读取 CSS 声明并使用cssTextCssRule 对象的属性来构建一个字符串,该字符串最终将使用Ajax POST 请求。服务器端是您的业务。

References:

参考:

Hope it helps

希望能帮助到你

回答by Nilesh

Recently I had the need to fix some jquery theme issue for Autocomplete widget. I wanted to change the background color of the autocomplete widget.

最近我需要修复一些自动完成小部件的 jquery 主题问题。我想更改自动完成小部件的背景颜色。

So I looked up the CSS and found that the autocomplete class is defined like this

于是查了一下css,发现autocomplete类是这样定义的

.ui-autocomplete { position: absolute; cursor: default; }   

So in my program I issue the following statement to change the class by adding the background property. Note that I keep the other attributes as it is otherwise it will break existing functionality

因此,在我的程序中,我发出以下语句以通过添加背景属性来更改类。请注意,我保留其他属性,否则会破坏现有功能

$("<style type='text/css'> .ui-autocomplete { position: absolute; cursor: default; background:black; color:white} </style>").appendTo("head");

回答by Blago

You should take this approach only if:

仅在以下情况下才应采用此方法:

  • You need to set the value to something that is impractical to enumerate (i.e. varying width in pixels) with class names
  • And you want to apply this style to elements that will be inserted in the DOM in the future
  • 您需要将该值设置为使用类名进行枚举(即以像素为单位的不同宽度)不切实际的值
  • 并且您希望将此样式应用于将来将插入到 DOM 中的元素

There is a jQuery plugin that does that: http://plugins.jquery.com/project/jquerycssrule

有一个 jQuery 插件可以做到这一点:http: //plugins.jquery.com/project/jquerycssrule

For a small project I worked on I extracted the bare essentials and created the following function:

对于我从事的一个小项目,我提取了基本要素并创建了以下函数:

function addCSSRule(sel, prop, val) {
    for(var i = 0; i < document.styleSheets.length; i++){
        var ss    = document.styleSheets[i];
        var rules = (ss.cssRules || ss.rules);
        var lsel  = sel.toLowerCase();

        for(var i2 = 0, len = rules.length; i2 < len; i2++){
            if(rules[i2].selectorText && (rules[i2].selectorText.toLowerCase() == lsel)){
                if(val != null){
                    rules[i2].style[prop] = val;
                    return;
                }
                else{
                    if(ss.deleteRule){
                        ss.deleteRule(i2);
                    }
                    else if(ss.removeRule){
                        ss.removeRule(i2);
                    }
                    else{
                        rules[i2].style.cssText = '';
                    }
                }
            }
        }
    }

    var ss = document.styleSheets[0] || {};
    if(ss.insertRule) {
        var rules = (ss.cssRules || ss.rules);
        ss.insertRule(sel + '{ ' + prop + ':' + val + '; }', rules.length);
    }
    else if(ss.addRule){
        ss.addRule(sel, prop + ':' + val + ';', 0);
    }
}

回答by Russ Cam

If I understand your question correctly, you would like to read through a CSS file, make changes to a class and then persist those changes by saving the file?

如果我正确理解您的问题,您想通读 CSS 文件,对类进行更改,然后通过保存文件来保留这些更改吗?

You can't do this with JavaScript/jQuery running from the client side; You can certainly change the font size of each individual element in the DOM that matches the CSS class.classname, like so

你不能用从客户端运行的 JavaScript/jQuery 来做到这一点;您当然可以更改 DOM 中与 CSS 类匹配的每个单独元素的字体大小.classname,如下所示

$('.classname').css('font-size','14px');

but client-side JavaScript cannot access the filesystem from the web browser, so you would need some other way (i.e. server-side code) to make changes to the CSS file itself.

但是客户端 JavaScript 无法从 Web 浏览器访问文件系统,因此您需要某种其他方式(即服务器端代码)来更改 CSS 文件本身。

回答by Vlad Sabev

You can also try JSS, it's worked wonderfully for me: https://github.com/Box9/jss

你也可以试试 JSS,它对我来说效果很好:https: //github.com/Box9/jss

Download and include jss.js in your HTML:

<script type="text/javascript" src="jss.js"></script>

Add new rule (or extend existing rule):

jss('.special', {
    color: 'red',
    fontSize: '2em',
    padding: '10px'
});

Retrieve existing rule:

jss('.special').get();

Returns:

{
    'color': 'red',
    'font-size': '2em',
    'padding-bottom': '10px',
    'padding-left': '10px',
    'padding-right': '10px',
    'padding-top': '10px'
}

Remove existing rule:

jss('.special').remove();

下载 jss.js 并将其包含在您的 HTML 中:

<script type="text/javascript" src="jss.js"></script>

添加新规则(或扩展现有规则):

jss('.special', {
    color: 'red',
    fontSize: '2em',
    padding: '10px'
});

检索现有规则:

jss('.special').get();

返回:

{
    'color': 'red',
    'font-size': '2em',
    'padding-bottom': '10px',
    'padding-left': '10px',
    'padding-right': '10px',
    'padding-top': '10px'
}

删除现有规则:

jss('.special').remove();

回答by Benibur

the DOM Level 2 lets manipulate directly the css rules of a stylesheet. ex :

DOM Level 2 允许直接操作样式表的 css 规则。前任 :

var ss = document.styleSheets[1];  // ref to the first stylesheet
ss.cssRules[0].style.backgroundColor="blue";  // modification of the 1rst rule

There are 2 interfaces :

有2个接口:

That make it possible to active/inactivate a stylesheet, remove a rule, add a rule etc... All the details here in MDM : Using_dynamic_styling_information

这使得激活/停用样式表、删除规则、添加规则等成为可能...... MDM 中的所有详细信息:Using_dynamic_styling_information

回答by lpfavreau

What you are looking to do is done by having a couple of themes on the server (theme1.css, theme2.css, theme3.css, etc.) and letting the user select the theme he likes. You can then save in the database with the user profile the theme the user chose (theme2.css). When the user then displays his page, you include at the top of the page the theme2.css instead of the theme default.css.

您要做的是通过在服务器上拥有几个主题(theme1.css、theme2.css、theme3.css 等)并让用户选择他喜欢的主题来完成。然后,您可以使用用户配置文件将用户选择的主题 (theme2.css) 保存在数据库中。当用户随后显示他的页面时,您将在页面顶部包含 theme2.css 而不是主题 default.css。

This would work well with server side technology such as PHP or ASP.NET or whatever you like. Of course, you could potentially use javascript to save a cookieon the user computer to remember his choice and use javascript again to include the filethat you remembered via the cookie.

这将适用于服务器端技术,例如 PHP 或 ASP.NET 或您喜欢的任何技术。当然,您可以潜在地使用 javascript在用户计算机上保存cookie以记住他的选择,并再次使用 javascript 来包含您通过 cookie 记住的文件

If you want to let the user manage exactly what applies to specific elements of the design (such as the color of the header, the font, etc.) you could again, using a server-side technology (better in this case in my opinion) or javascript save things like header=blue, font=Arial and using jQueryapply what was stored to your page.

如果您想让用户准确地管理适用于设计的特定元素的内容(例如标题的颜色、字体等),您可以再次使用服务器端技术(在我看来,在这种情况下更好) 或 javascript 保存诸如 header=blue, font=Arial 之类的内容,并使用jQuery将存储的内容应用到您的页面。

Hope it gives you an overview.

希望它能给你一个概述。

回答by studgeek

On a semi-related note, also see my answer about changing LESS variables which will result in updated CSS rules. Depending on your case that may be more useful since a single LESS variable can drive a lot of CSS rules.... https://stackoverflow.com/a/9491074/255961

在半相关的注释中,另请参阅我关于更改 LESS 变量的答案,这将导致更新的 CSS 规则。根据您的情况,这可能更有用,因为单个 LESS 变量可以驱动很多 CSS 规则...... https://stackoverflow.com/a/9491074/255961

回答by user511941

not sure about changing the class properties I came here looking for an answer to that myself and seems there are a few answers for that already, as for saving you could use jquery $.post method to send a form containing changes or $.get with url encoded values to then write to the new css file using PHP fwrite, or file_put_contents. make sure you restrict access to this feature or ensure values meet a certain criteria before storing any data.

不确定更改类属性我来到这里寻找自己的答案,似乎已经有一些答案,至于保存,您可以使用 jquery $.post 方法发送包含更改或 $.get 的表单url 编码的值,然后使用 PHP fwrite 或 file_put_contents 写入新的 css 文件。在存储任何数据之前,请确保限制对该功能的访问或确保值满足特定标准。

回答by Viliam

For the first part, I usually specify a style block and switch it on/off with jQuery. For example:

对于第一部分,我通常指定一个样式块并使用 jQuery 打开/关闭它。例如:

<style type="text/css" id="my-style" media="all">
    .classname{color:red; font-size:14px;}
</style>

Then you can to the switching by setting the disabled attribute, such as:

然后就可以通过设置disabled属性来切换了,比如:

$('#my-style').prop('disabled', true);
$('#my-style').prop('disabled', false);