使用变量引用样式属性 [英] referring to a style property using a variable

查看:61
本文介绍了使用变量引用样式属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In the project I am working on, I have to access the style property of an element using a variable. For example: Normally, to change the background color of an element we write:

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

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

But, If I declare a variable holding "backgroundColor" and then I want to change the property of background color by referring to the value in this this variable, then how could it be done. I tried these:

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

但是没有用.我不确定是否可以通过其他任何方式完成此任务.如果对此有任何解决方案,请回答.

But it didn't work. I am not sure of any other way I can accomplish this. If there is any solution for this, then please answer.

推荐答案

使用[]表示法,例如

element.style[property] = 'blue';

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

这篇关于使用变量引用样式属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆