引用使用变量的样式属性

时间:2013-09-26 05:44:23

标签: javascript css

在我正在处理的项目中,我必须使用变量访问元素的style属性。    例如:通常,要更改我们编写的元素的背景颜色:

var element = document.getElementById("element");
element.style.backgroundColor = "blue";

但是,如果我声明一个持有“backgroundColor”的变量,然后我想通过引用此变量中的值来更改背景颜色的属性,那么怎么做呢。     我试过这些:

var property = "backgroundColor";
eval(element.style.property = "blue");

但它没有用。我不确定我能做到的任何其他方式。如果有任何解决方案,请回答。

4 个答案:

答案 0 :(得分:9)

使用[]表示法,例如

element.style[property] = 'blue';

请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Objects_and_properties

答案 1 :(得分:1)

您可以执行以下操作:

var property = "backgroundColor" ;

element.style[property] = "blue" ;

这样您就可以访问background属性

答案 2 :(得分:1)

这是因为它发出甜蜜的错误,

Uncaught SyntaxError: Unexpected string 

document.getElementById("element").style - > Style Object [object CSSStyleDeclaration]

backgroundImagestyle Object的属性。

要访问样式对象的属性,您可以使用[]

var property = "backgroundColor";
element.style[property] = 'blue'; // will set property of element.

答案 3 :(得分:0)

有没有办法不仅用样式对象,而且用它的值来获取 var ? 类似于下面的代码。我知道这段代码不起作用,我写它只是为了更好地解释我的要求。

var property = "backgroundColor = "blue" ";
element.style[property];