2012-03-22 76 views
1

是否以任何方式使用JavaScript更改css类模型?使用JavaScript更改css类模型

伪代码:

function updateClass(className, newData) { 
    cssInterface.alterClass(className, newData); 
} 

的className是类,这是应该的名称被改变(如“.footer”)和newData是新类的内容(如边界“1px的固体粉;“)。这个目标实际上只是为了节省空间:我正在使用CSS3动画,所以改变受其类的影响的元素的一个属性将终止它的动画 - (在我的案件)字体大小不会再改变。使用不同的类将需要为所有受影响的元素创建一组全新的类,我想避免这种情况。

我不是通过

element.className = "foo"; 

寻找一个改变
element.style.fontSize = "15pt"; 

感谢您的帮助,球员:)

+0

jquery呢? – 2012-03-22 22:04:11

+0

是的,如果你知道规则在哪个样式表中(你可以迭代所有的样式表我猜),并且该样式表由sameDomain托管 – Esailija 2012-03-22 22:09:13

回答

0

查看我的回答here。回答你的问题:是的,这是可能的。

@ CSS3:我在我的一个html5实验中完全一样。我创建了一个额外的<style>元素,并将其contentText更改为我需要的CSS类定义。当然改变cssRule对象将:-)

+0

它实际上是style元素的innerText属性(它要完成答案可以使用ID或任何其他),但它的工作 - 非常感谢! – brickBreaker 2012-03-23 22:26:30

+0

对,这个属性似乎是依赖于浏览器的。 IE似乎需要'styleSheets.cssText',其他人则对TextNodes很幸运。还没有尝试过'innerHTML' /'innerText'。 – Bergi 2012-03-27 17:41:14

+0

关于Internet Explorer只有一件事要说: [9gag](http:// 9gag。com/gag/104588) 我想,'innerHTML'将不起作用 - 毕竟它是css。 – brickBreaker 2012-03-28 20:35:48

0

至于我可以告诉CSS对象模型不能轻易告诉你是否已经为特定类的现有样式规则,但你可以很容易地添加新的规则为类,它会覆盖任何该风格的前一个声明。

我找到了一个creating dynamic stylesheets的例子。

1

更清洁这里是我的功能来做到这一点...

function changeCSS(typeAndClass, newRule, newValue)  // modify the site CSS (if requred during scaling for smaller screen sizes) 
{ 
    var thisCSS=document.styleSheets[0]         // get the CSS for the site as an array 
    var ruleSearch=thisCSS.cssRules? thisCSS.cssRules: thisCSS.rules // work out if the browser uses cssRules or not 
    for (i=0; i<ruleSearch.length; i++)         // for every element in the CSS array 
    { 
     if(ruleSearch[i].selectorText==typeAndClass)     // find the element that matches the type and class we are looking for 
     { 
      var target=ruleSearch[i]         // create a variable to hold the specific CSS element 
      var typeExists = 1; 
      break;              // and stop the loop 
     } 
    } 
    if (typeExists) 
    { 
     target.style[newRule] = newValue;         // modify the desired class (typeAndClass) element (newRule) with its new value (newValue). 
    } 
    else 
    { 
     alert(typeAndClass + " does not exist."); 
    } 
} 

与(例如)

changeCSS("div.headerfixed","-moz-transform-origin", "100% 0%"); 

希望这有助于调用。