如何使用javascript修改CSS样式表(不是如何更改元素的样式表)

时间:2011-11-14 21:44:35

标签: javascript

我正在尝试通过设置其cssText属性来修改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中。

1 个答案:

答案 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";
}