改变CSS类定义

假设我有这个课程:

.MyClass{background:red;} 

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

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

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

谢谢。

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

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

很难找到你想要的规则,因为你必须遍历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); } } 

你有2个选择

  1. 添加一个覆盖此.MyClass的新样式表
  2. 有一个具有不同属性的第二个类,并更改这些元素上的类名

看看你的问题,我认为更好的方法是使用JavaScript切换MyClass ,而不是动态地更改类的属性。

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

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

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

例如

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