简体   繁体   English

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

[英]How can I change the css class rules using jQuery?

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.我想要做的是使用 jQuery 即时更改 css class 规则。

     .classname{color:red; .classname{颜色:红色; font-size:14px;}字体大小:14px;}

    In example above I have a class named .classname now using jQuery I want to change the font size only not color with in .classname not by adding css inline.在上面的示例中,我有一个名为.classname的 class 现在使用 jQuery 我只想更改字体大小而不是使用.classname中的颜色,而不是通过添加 css 内联。

  2. I want to create and save .classname change to a file remember there will be complete stylesheet or no of classnames that will be save in file.我想创建.classname更改并将其保存到文件中,记住将有完整的样式表或没有将保存在文件中的类名。

How I can do this the easiest and better way?我怎样才能以最简单和更好的方式做到这一点?

Thanks!谢谢!

As far as I know there's no jQuery way to do this.据我所知,没有 jQuery 方法可以做到这一点。 There might be some jQuery plugin for this but I don't know.可能有一些 jQuery 插件,但我不知道。

Basically, what you're trying to achieve in your first question is possible using the styleSheets property of the document object.基本上,您在第一个问题中尝试实现的目标可以使用document object 的styleSheets属性来实现。 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.它比这要复杂一些,因为您需要走到一个相当深的 object 链,但仍然适用于包括 Internet Explorer 6 在内的所有主要浏览器。下面是一个概念证明。 The CSS is inside a STYLE tag, but works with external CSS just as well. CSS 位于 STYLE 标签内,但也可与外部 CSS 一起使用。 I'll let you do the abstractions.我会让你做抽象。

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 cssText property of a CssRule object in order to build a string which will eventually be sent to the server using a Ajax POST request.对于您的第二个问题,我没有时间编写解决方案,但这将涉及阅读 CSS 声明,并使用 CssRule object 的cssText属性来构建一个字符串,该字符串最终将发送到服务器使用Ajax POST 请求。 The server side is your business.服务器端是您的业务。

References:参考:

Hope it helps希望能帮助到你

Recently I had the need to fix some jquery theme issue for Autocomplete widget.最近我需要为自动完成小部件修复一些 jquery 主题问题。 I wanted to change the background color of the autocomplete widget.我想更改自动完成小部件的背景颜色。

So I looked up the CSS and found that the autocomplete class is defined like this于是我查了一下 CSS 发现自动补全 class 是这样定义的

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

So in my program I issue the following statement to change the class by adding the background property.因此,在我的程序中,我发出以下语句,通过添加背景属性来更改 class。 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");

You should take this approach only if:只有在以下情况下,您才应该采用这种方法:

  • You need to set the value to something that is impractical to enumerate (ie varying width in pixels) with class names您需要使用 class 名称将值设置为无法枚举的值(即以像素为单位的不同宽度)
  • 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:

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);
    }
}

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 文件,对 class 进行更改,然后通过保存文件来保留这些更改?

You can't do this with JavaScript/jQuery running from the client side;你不能用从客户端运行的 JavaScript/jQuery 来做到这一点; You can certainly change the font size of each individual element in the DOM that matches the CSS class .classname , like so您当然可以更改与 CSS class .classname匹配的 DOM 中每个单独元素的字体大小,就像这样

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

but client-side JavaScript cannot access the filesystem from the web browser, so you would need some other way (ie server-side code) to make changes to the CSS file itself.但是客户端 JavaScript 无法从 web 浏览器访问文件系统,因此您需要一些其他方式(即服务器端代码)来更改 CSS 文件本身。

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:下载 jss.js 并将其包含在您的 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();

the DOM Level 2 lets manipulate directly the css rules of a stylesheet. DOM Level 2 允许直接操作样式表的 css 规则。 ex:前任:

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

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. 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).然后,您可以使用用户配置文件将用户选择的主题 (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.当用户然后显示他的页面时,您在页面顶部包含 theme2.css 而不是主题 default.css。

This would work well with server side technology such as PHP or ASP.NET or whatever you like.这适用于服务器端技术,例如 PHP 或 ASP.NET 或任何您喜欢的。 Of course, you could potentially use javascript to save a cookie on the user computer to remember his choice and use javascript again to include the file that you remembered via the cookie.当然,您可能会使用 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 jQuery apply what was stored to your page.如果您想让用户准确管理适用于设计特定元素的内容(例如 header 的颜色、字体等),您可以再次使用服务器端技术(我认为在这种情况下更好) 或 javascript 保存诸如 header=blue、font=Arial 之类的内容并使用jQuery应用存储到您页面的内容。

Hope it gives you an overview.希望它能给你一个概述。

For the first part, I usually specify a style block and switch it on/off with jQuery.对于第一部分,我通常指定一个样式块并使用 jQuery 打开/关闭它。 For example:例如:

<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);

You can use YUI Stylesheet Utility.您可以使用 YUI 样式表实用程序。

http://yuilibrary.com/yui/docs/stylesheet/ http://yuilibrary.com/yui/docs/stylesheet/

It works grate!它工作得很好!

As styles applied to the head section 'overload' each other, their late append() with styles for all relevant elements will be used, unless there was !important involved earlier.由于 styles 彼此应用到头部“重载”,因此将使用所有相关元素的后期append()以及 styles,除非之前有!important涉及。

The function used for assigning the css-content should be text() not html() to prevent accidental injections of code用于分配 css 内容的 function 应该是text()而不是html()以防止意外注入代码

var dynamic_css = function(class_name){
  return '.' + class_name + ' {color:red; font-size:14px;}';
}
var styles = $('<style type="text/css">');
styles.text(dynamic_css('my_classname'));
$('html head').append(styles);

later:之后:

styles.remove();

it also works well to assign a class to the styles element to identify it later将 class 分配给 styles 元素以在以后识别它也很有效

On a semi-related note, also see my answer about changing LESS variables which will result in updated CSS rules.在半相关的说明中,另请参阅我关于更改 LESS 变量的答案,这将导致更新的 CSS 规则。 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 规则.... https://stackoverflow.com/a/9491074/255961

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.不确定是否要更改 class 属性我来这里寻找自己的答案,似乎已经有一些答案,至于保存,您可以使用 jquery $.post 方法发送包含更改或 $.get 的表单url 编码值,然后使用 PHP fwrite 或 file_put_contents 写入新的 css 文件。 make sure you restrict access to this feature or ensure values meet a certain criteria before storing any data.在存储任何数据之前,请确保您限制对此功能的访问或确保值符合特定标准。

I used the addClass of jquery: http://api.jquery.com/addClass/ and then set the class as the attributes i want to change. I used the addClass of jquery: http://api.jquery.com/addClass/ and then set the class as the attributes i want to change.

I am pretty sure you can't change the rules inside an existing style.我很确定您不能更改现有样式中的规则。 Even firebug won't let you do this.即使萤火虫也不会让你这样做。 You can style an element or set of elements, you can assign and unassign classes, but I don't think you can alter existing classes.您可以设置一个元素或一组元素的样式,可以分配和取消分配类,但我认为您不能更改现有的类。 In order to do what you are asking you will need to maintain some sort of associative array that records proposed changes to existing classes and then to save those changes you will need to upload to a server that can then offer a link for download to the client.为了执行您所要求的操作,您需要维护某种关联数组来记录对现有类的建议更改,然后保存这些更改,您需要上传到服务器,然后服务器可以提供下载到客户端的链接.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM