2014-05-09 53 views
0

這是如何動態地更改選擇規則的簡化版本:變化樣式規則選擇動態

http://jsfiddle.net/vsync/SaQy6/

對於送禮者內嵌樣式:

<style type='text/css' id='myStyle'> 
    ul > li{} 
</style> 

嘗試改變選擇器

var styleTag = document.querySelector('#myStyle'); 
// the style sheet in the style tag 
var sheet = styleTag.sheet ? styleTag.sheet : styleTag.styleSheet, 
    // the first rule in the style sheet 
    rules = sheet.cssRules ? sheet.cssRules : sheet.rules; 

rules[0].selectorText = 'ul > li:nth-child(2)'; 
rules[0].style.cssText = 'background:red'; 

也不selectorTextcssText工作設置選擇器dynbamically。

然後,我在MDN上讀到selectorText是隻讀的,我失去了如何切換選擇器,而不必刪除整個樣式元素並創建一個新的。 可以選擇完全刪除規則並插入新規則,但它非常不規範。有任何想法嗎?

回答

1

演示 - http://jsfiddle.net/vsync/SaQy6/6/

跨瀏覽器的方式:

var styleTag = document.querySelector('#myStyle'); 
// the style sheet in the style tag 
var sheet = styleTag.sheet ? styleTag.sheet : styleTag.styleSheet, 
    rules = sheet.cssRules ? sheet.cssRules : sheet.rules; 

if(sheet.cssRules){ 
    sheet.deleteRule(0); // deletes a rule at index 0 
    sheet.insertRule("ul > li:nth-child(2n){background:red}", 0); 
} 
else{ 
    sheet.removeRule(0); // deletes a rule at index 0 
    sheet.addRule("ul > li:nth-child(2n)", 'background:red', 0); 
} 
+0

此工作正常,如果只有一個樣式規則,但是是多麼普遍?一般來說,追蹤哪個規則是哪個規則,如果有一些規則應該是動態的,則很難。規則不是默認命名的,似乎沒有規定它們的命名。我看到的唯一命名方案是爲每個動態規則製作一個單獨的樣式表,並帶有一個id,然後該技術可以正常工作。 – Victoria

+0

@維多利亞 - 所以你可以刪除所有這些,然後重新插入。如果你有10個規則,只需循環和刪除10次..這是我現在能想到的唯一解決方案 – vsync

+0

是的,如果所有10個規則都已知,並且在已知的樣式塊中,那將起作用。儘管如此,模塊化代碼可能不知道全部10條規則。因此,在單獨的