javascript 更改 CSS 类定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10643495/
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-10-26 10:32:16  来源:igfitidea点击:

changing CSS class definition

javascriptjquerycss

提问by frenchie

Suppose I have this class:

假设我有这个类:

.MyClass{background:red;}

This class applies to several divs. I want to change the color of the background to orange by changing the color defined in MyClass.

此类适用于多个 div。我想通过更改 MyClass 中定义的颜色将背景颜色更改为橙​​色

Now, I know I could do $('.MyDiv').css('background', 'orange');

现在,我知道我可以做到 $('.MyDiv').css('background', 'orange');

But my question is really this: how do I change the CSS class definition so that MyClass elements now have background:orange;? I want to be able to change several CSS color properties from one color to another.

但我的问题实际上是这样的:如何更改 CSS 类定义,以便 MyClass 元素现在具有background:orange;?我希望能够将多个 CSS 颜色属性从一种颜色更改为另一种颜色。

Thanks.

谢谢。

采纳答案by chaos

Actually altering your stylesheet is pretty challenging. Much more easily, though, you can switch outyour stylesheet for a different one, which may be sufficient for your purposes. See How do I switch my CSS stylesheet using jQuery?.

实际上改变你的样式表是非常具有挑战性的。但是,更容易的是,您可以将样式表切换为不同的样式表,这可能足以满足您的目的。请参阅如何使用 jQuery 切换我的 CSS 样式表?.

For actually altering the stylesheet content, How to change/remove CSS classes definitions at runtime?will get you started.

对于实际更改样式表内容,如何在运行时更改/删除 CSS 类定义?会让你开始。

回答by user3257710

It is difficult to find the rule you want because you have to iterate through the document.styleSheets[i].cssRulesarray. (and compare your class name with the selectorTextattribute)
So my solution to this problem is to add a new CSS class, remove the old CSS class from the HTML element and add this class instead of it.

很难找到您想要的规则,因为您必须遍历document.styleSheets[i].cssRules数组。(并将您的类名与selectorText属性进行比较)
所以我对这个问题的解决方案是添加一个新的 CSS 类,从 HTML 元素中删除旧的 CSS 类并添加这个类而不是它。

var length = getCssRuleLength();
var newClassName = "css-class-name" + length;

//remove preview css class from html element.
$("#your-html-element").removeClass("css-class-name");
$("#your-html-element").removeClass("css-class-name" + (length-1));

$("#your-html-element").addClass(newClassName);

//insert a css class
insertCssRule("." + newClassName + ' { max-width: 100px; }', length);


function getCssRuleLength() {
 var length = 0;
 if (document.styleSheets[1].cssRules) {
  length = document.styleSheets[1].cssRules.length;
 } else if (document.styleSheets[1].rules) { //ie
  length = document.styleSheets[1].rules.length;
 }
 return length;
}
function insertCssRule(rule, index) {
 if (document.styleSheets[1].cssRules) {
  document.styleSheets[1].insertRule(rule, index);
 } else if (document.styleSheets[1].rules) { //ie
  document.styleSheets[1].addRule(rule, index);
 }
}

回答by GreenRock

Here's my answer in case anyone stumbles upon this. Give your elements a new class name that doesn't already exist, then dynamically add a style segment:

这是我的答案,以防万一有人偶然发现这一点。给你的元素一个不存在的新类名,然后动态添加一个样式段:

var companyColor = 'orange' //define/fetch the varying color here
var style = '<style>.company-background {background-color: ' + companyColor + '; color: white;}</style>';
$('html > head').append($(style));

//give any element that needs this background color the class "company-background"

回答by Ibu

You have 2 options

你有2个选择

  1. add a new stylesheet that overrides this .MyClass
  2. have a second class with the different property, and change the class Name on these elements
  1. 添加一个覆盖此的新样式表 .MyClass
  2. 有一个具有不同属性的第二个类,并更改这些元素上的类名称

回答by shingokko

Looking at your question, I think a better approach is to switch MyClasswith something else using JavaScript rather than to change the properties of the class dynamically.

看着您的问题,我认为更好的方法是使用 JavaScript将MyClass与其他内容切换,而不是动态更改类的属性。

But if you are still keen you can switch CSS stylesheets with jQuery http://www.cssnewbie.com/simple-jquery-stylesheet-switcher/

但是,如果您仍然热衷,您可以使用 jQuery http://www.cssnewbie.com/simple-jquery-stylesheet-switcher/切换 CSS 样式表

回答by tqwhite

var changeClassProperty = function(sheetName, className, propertyName, newValue, includeDescendents) {
        var ending = '$';
        setValue = '';
        if (includeDescendents === true) {
            ending = '';
        }
        if (typeof(newValue) != 'undefined') {
            setValue = newValue;
        }
        var list = document.styleSheets;
        for (var i = 0, len = list.length; i < len; i++) {
            var element = list[i];
            if (element['href'] && element['href'].match(new RegExp('jquery\.qtip'))) {
                var cssRules = element.cssRules;
                for (j = 0, len2 = cssRules.length; j < len2; j++) {
                    var rule = cssRules[j];
                    if (rule.selectorText.match(new RegExp(className + ending))) {
                        cssRules[j].style.backgroundColor = setValue;
                        console.log(cssRules[j].style.backgroundColor);
                    }
                }
            }
        }
    }
changeClassProperty('jquery.qtip', 'tipsy', 'backgroundColor', 'yellow');

回答by xbonez

You'd be much better off adding and removing classes instead of attempting to change them.

添加和删​​除类而不是尝试更改它们会更好。

For example

例如

.red {
    background: red;
}

.orange {
    background: orange;
}

$('#div').click(function(){
    $(this).removeClass('red').addClass('orange');
});