2012-03-22 52 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%"); 

希望這有助於調用。