浏览器是怎么解析CSS的呢? 首先让我们来认识一下CSSStyleDeclaration,DOM CSS的一员,也是分量最重的一个。所有的CSS都会被解析到CSSStyleDeclaration中,你可以通过它去读取CSS属性更改CSS属性。 无论你在哪里写CSS,无论你写了什么CSS,浏览器最后都会解析成一个或数个styleSheet,每个styleSheet又包含一个或多个 cssRule,每个cssRule又包含零个或一个或多个style(即CSSStyleDeclaration)。这些 CSSStyleDeclaration会和其他styleSheet中CSSStyleDeclaration以及相应标签中的 CSSStyleDeclaration进行比较,根据权重的不同,最后生成computedStyle即最终我们所看到的样式。 举个例子: <style type=”text/css”> @import url(print.css); b{color:yellow;} </style> 上面的代码就会生成一个styleSheet,这个styleSheet中有两个cssRule,分别是“@import url(print.css);”和“b{color:yellow;}”,第一个cssRule中没有style(会有一个子styleSheet), 第二个cssRule中包含一个style是“color:yellow;”。 注意:每个style标签都会生成一个独立的styleSheet。 另外需要说明的一点,也是容易混淆的一点: 其他标签中的style属性中的CSS不能看作是真正的CSS本身,如:<b style=”color:red”></b>,它只是标签style属性的数值,浏览器会根据这个值去更改真正的CSSStyleDeclaration。 其实大家平时经常在和CSSStyleDeclaration打交道,比如:this.style.display=”none” ,这条JS通常我们会简单的理解成更改this对象的style属性中的值,即style=”display:none”,事实上没那么简单。 从底层来说,这条JS是用来更改CSSStyleDeclaration的,这条语句中的style实际就是CSSStyleDeclaration,浏 览器首先通过这条JS更改CSSStyleDeclaration中display的值,然后CSSStyleDeclaration的cssText值 会跟着被修改,最后才传达到this标签的style属性。 这也是为什么this.style.color=”red!important”无法更改color值的原因,!important只是在生成 computedStyle时比较CSS权重用的,CSSStyleDeclaration中的color值不会有!important的,如果给它了, 会被认为是非法值,因此this.style.color=”red!important”是无效的。 更改CSSStyleDeclaration可以有多种方式,上面的this.style.display=”none”就是一种,也是最常用的最简单的 一种,在某些特殊情况下我们也可以这样来改变:this.style.cssText=”display:none” 或者 this.setAttribute(”style”,”display:none”) 。 这里this.setAttribute(”style”,”display:none”)又是另外一种情况了,它先去更改style属性的值,然后再更改CSSStyleDeclaration的值。