简体   繁体   English

动态应用css样式

[英]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=colorstyle2= 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';

You need to use 你需要使用

header.style.color
&
header.style.fontFamily, header.style.fontSize

to change the styles you mentioned. 改变你提到的风格。

You can also use CSS Text 您也可以使用CSS Text

header.style.cssText 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM