我们接着做试验。
在代码中定义三种不同形式的基本的CSS,如下:
test1.mxml
<?xml version="1.0" encoding="utf-8"?>
<!-- styles/SelectorsTest.mxml -->
<s:Application
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:s="library://ns.adobe.com/flex/spark">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Style>
@namespace s "library://ns.adobe.com/flex/spark";
@namespace mx "library://ns.adobe.com/flex/mx";
s|TextInput{
color:#112233;
}
.MyStyle{
color:#445566;
}
#bnt{
color:#778899;
}
</fx:Style>
<fx:Script>
<![CDATA[
public function showSelectors():void {
var selectors:Array = styleManager.selectors;
msg.text = "所有的选择器列表如下(" + selectors.length + ")\n";
for (var i:int = 0; i < selectors.length; i++) {
msg.text += "\n" + selectors[i];
}
}
]]>
</fx:Script>
<s:Button id="btn" label="Show Selectors" click="showSelectors()" styleName="MyStyle"/>
<s:TextArea id="msg" width="100%" height="100%"/>
</s:Application>
执行结果如下图,我们自定义的三种类型的CSS赫然纸上
查看编译器自动生成的代码,摘录如下:
test1-generated.as
var conditions:Array;
var condition:CSSCondition;
var selector:CSSSelector;
selector = null;
conditions = null;
conditions = null;
selector = new CSSSelector("spark.components.TextInput", conditions, selector);
// spark.components.TextInput
style = styleManager.getStyleDeclaration("spark.components.TextInput");
if (!style)
{
style = new CSSStyleDeclaration(selector, styleManager);
}
if (style.factory == null)
{
style.factory = function():void
{
this.color = 0x112233;
};
}
selector = null;
conditions = null;
conditions = [];
condition = new CSSCondition("class", "MyStyle");
conditions.push(condition);
selector = new CSSSelector("", conditions, selector);
// .MyStyle
style = styleManager.getStyleDeclaration(".MyStyle");
if (!style)
{
style = new CSSStyleDeclaration(selector, styleManager);
}
if (style.factory == null)
{
style.factory = function():void
{
this.color = 0x445566;
};
}
selector = null;
conditions = null;
conditions = [];
condition = new CSSCondition("id", "bnt");
conditions.push(condition);
selector = new CSSSelector("", conditions, selector);
// #bnt
style = styleManager.getStyleDeclaration("#bnt");
if (!style)
{
style = new CSSStyleDeclaration(selector, styleManager);
}
if (style.factory == null)
{
style.factory = function():void
{
this.color = 0x778899;
};
}
由此看见,编译器为每个CSS样式都单独生成了一段代码。
如果我们不用FlashBuilder,而是纯手工来编写,也是可行的,就是慢点儿,呵呵。