在我正在处理的项目中,我必须使用变量访问元素的style属性。 例如:通常,要更改我们编写的元素的背景颜色:
var element = document.getElementById("element");
element.style.backgroundColor = "blue";
但是,如果我声明一个持有“backgroundColor”的变量,然后我想通过引用此变量中的值来更改背景颜色的属性,那么怎么做呢。 我试过这些:
var property = "backgroundColor";
eval(element.style.property = "blue");
但它没有用。我不确定我能做到的任何其他方式。如果有任何解决方案,请回答。
答案 0 :(得分:9)
使用[]
表示法,例如
element.style[property] = 'blue';
答案 1 :(得分:1)
您可以执行以下操作:
var property = "backgroundColor" ;
element.style[property] = "blue" ;
这样您就可以访问background
属性
答案 2 :(得分:1)
这是因为它发出甜蜜的错误,
Uncaught SyntaxError: Unexpected string
document.getElementById("element").style
- > Style Object [object CSSStyleDeclaration]
和backgroundImage
是style Object
的属性。
要访问样式对象的属性,您可以使用[]
var property = "backgroundColor";
element.style[property] = 'blue'; // will set property of element.
答案 3 :(得分:0)
有没有办法不仅用样式对象,而且用它的值来获取 var ? 类似于下面的代码。我知道这段代码不起作用,我写它只是为了更好地解释我的要求。
var property = "backgroundColor = "blue" ";
element.style[property];