2011-11-14 48 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

相关问题