2011-11-14 71 views
0

我試圖通過設置其屬性cssText修改CSS樣式表,但它沒有堅持。如何使用JavaScript修改CSS樣式表(不是我如何改變元素的樣式表)

Test Page

推進此按鈕應可以切換從一個紅色箭頭其外觀以黑色箭頭和黑色的,但沒有改變。這出現在JavaScript日誌中:

 
changed cssText from .movebutton button { width: 100px; height: 100px; background-image: url("redarrow.svg"); } to .movebutton button { width: 100px; height: 100px; background-image: url("redarrow.svg"); } should be .movebutton button { width: 100px; height: 100px; background-image: url("blackarrow.svg"); } 

changed cssText from .movebutton button { width: 100px; height: 100px; background-image: url("redarrow.svg"); } to .movebutton button { width: 100px; height: 100px; background-image: url("redarrow.svg"); } should be .movebutton button { width: 100px; height: 100px; background-image: url("redarrow.svg"); } 

changed cssText from .movebutton button { width: 100px; height: 100px; background-image: url("redarrow.svg"); } to .movebutton button { width: 100px; height: 100px; background-image: url("redarrow.svg"); } should be .movebutton button { width: 100px; height: 100px; background-image: url("blackarrow.svg"); } 

changed cssText from .movebutton button { width: 100px; height: 100px; background-image: url("redarrow.svg"); } to .movebutton button { width: 100px; height: 100px; background-image: url("redarrow.svg"); } should be .movebutton button { width: 100px; height: 100px; background-image: url("redarrow.svg"); } 

所以基本上看起來好像這個改變並沒有粘住。這是在Firefox 7.0.1中。 ?

+2

要改變相關元素上的類比重寫樣式表要容易得多。如何爲類設置'.movebutton red'和'.movebutton black'?足夠容易扎那兩個一起在樣式表,然後你只之間切換紅/黑,這是很容易,對重寫樣式表,這是更難。 –

+0

我知道我可以解決此問題通過更改類,我只是想知道爲什麼沒有工作,以供將來參考。 –

回答

0

爲什麼你想在運行時更改樣式定義.. 的更快,更方便和更清潔的方式來實現,這是在CSS定義來定義你的風格:

.movebuttonRed { width: 100px; height: 100px; background-image: url(http://www.tupari.net/jstest/redarrow.svg);} 
.movebuttonBlack { width: 100px; height: 100px; background-image: url(http://www.tupari.net/jstest/blackarrow.svg);} 

,然後改變使用Javascript的元素className屬性 -

if (document.getElementById("mybutton").className == "movebuttonRed") { 
    document.getElementById("mybutton").className = "movebuttonBlack"; 
} else { 
    document.getElementById("mybutton").className = "movebuttonRed"; 
} 
+0

對,我知道我可以那樣做,而且我可能會這樣做。我只想知道爲什麼改變樣式表不起作用。 –

+0

樣式表由瀏覽器在加載頁面時處理。將樣式表定義看作其他編程語言中的常量。 是沒有意義去了解在運行時更改樣式定義。這些都是定義,不是動態的變量。 –

+0

@ Zohar.Babin完全錯誤。看到這個:http://stackoverflow.com/questions/2011176/changing-a-stylesheet-using-jquery – user1514042

相關問題