[英]Applying css style dynamically
hello I extract the style attributes names from xml file (color and font in this case ) so at the end I've got variable style1=color
and style2= font
; 你好我从xml文件中提取样式属性名称(在这种情况下是颜色和字体),所以最后我有变量
style1=color
和style2= font
;
But when I wrote the following code - it doesn't work - the programme says that style1
is undefined. 但是当我编写以下代码时 - 它不起作用 - 程序说
style1
是未定义的。 How can I change that? 我怎么能改变呢?
var header=document.createElement("div");
header.setAttribute("id", "header1");
header.style.style1=headerstyles[i].nodeValue;
Since style1
is a variable holding the actual css property name like color/font, you cannot use the .
由于
style1
是一个包含颜色/字体等实际css属性名称的变量,因此无法使用.
(dot) operator, you need to use []
to specify the property. (点)运算符,您需要使用
[]
来指定属性。
header.style[style1]=headerstyles[i].nodeValue;
Because style itself is an object. 因为风格本身就是一个对象。 What you want is:
你想要的是:
header.style.setAttribute('color','red'); header.style.setAttribute( '颜色', '红');
But IE doesn't support setAttribute for style objects. 但IE不支持样式对象的setAttribute。
So use the fully cross-browser supported: 所以使用完全跨浏览器支持:
header.style.cssColor = 'red'; header.style.cssColor ='red';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.