Silverlight 是Microsoft推出的一項全新的跨平臺與跨瀏覽器的客戶端技術,能設計與開發出具備豐富多媒體效果的可交互WEB程序.簡單的幾句代碼就能快速的展示出非凡的效果.大家可以嘗試以下代碼,感受一下Silverlight的效果:
使用說明:代碼直接來自奚江華的<Silverlight 完美入門>一書,總共五個文件,Test.html / Test.xaml / Silverlight.js / Test.html.js / Test.xaml.js 可以看到,Silverlight的技術新在Test.xaml裏面,其他的html和javascript技術都是我們之前已經有的,所以大家不需要那麼害怕Silverlight.Test.xaml裏面的代碼也有限,看下圖:(實際上不是三個黃色的小球,而是一個黃色小球從左上角漸變出來,圖片顯示的小黃球運動和變化的軌跡)
如果不用Silverlight,大家估計只能用FLASH或者圖片GIF來設計了,現在有了Silverlight,幾句代碼就可以實現.好了,下面大家可以把代碼拷貝下來,五個文件存到同一目錄下,然後打開Test.html,即可看到Silverlight的效果.
代碼不需要看懂,只要知道以下幾點:
1)許多2D和絢目的效果,以前HTML等語言無法實現,只能藉助FLASH和PHTOTOSHOP特別處理過的效果,現在Silverlight用代碼就可以實現,且易於搜索引擎的收錄.
2)Silverlight並不複雜,涉及到的新技術只有XAML,其他的HTML,JAVASCRITP,DOM等都是老面孔.
3)無論asp/asp.net/php/jsp網站都可以和Silverlight完美的結合使用,沒有"門戶"之見.(實驗過下面的小例子大家應該就能感受到),因爲Silverlight是客戶端程序,不在服務器端,這點非常重要.
4)瀏覽Silverlight站,需要安裝Silverlight客戶端程序,大家可以到 http://www.microsotf.com/silverlight/install.aspx 會自動檢測你的電腦是否具備瀏覽Silverlight站的功能,如果不可以會提示Install Now,大家安裝就是了,類似於打開含有FLASH的網站需要裝FLASH播放插件一樣.
好啦,大家先來試試看,自己的第一個Silverlight程序!!!
Silverlight.js(包含用於下載和實例化 Silverlight 控件的代碼)
...{};Silverlight._silverlightCount=0;Silverlight.ua=null;Silverlight.available=false;Silverlight.fwlinkRoot="http://go.microso
ft.com/fwlink/?LinkID=";Silverlight.StatusText="Get Microsoft
Silverlight";Silverlight.EmptyText="";Silverlight.detectUserAgent=function()...{var
a=window.navigator.userAgent;Silverlight.ua=...{OS:"Unsupported",Browser:"Unsupported"};if(a.indexOf("Windows NT")>=0)
Silverlight.ua.OS="Windows";else if(a.indexOf("PPC Mac OS X")>=0)Silverlight.ua.OS="MacPPC";else if(a.indexOf("Intel Mac OS
X")>=0)Silverlight.ua.OS="MacIntel";if(Silverlight.ua.OS!="Unsupported")if(a.indexOf("MSIE")>=0)...{if
(navigator.userAgent.indexOf("Win64")==-1)if(parseInt(a.split("MSIE")[1])>=6)Silverlight.ua.Browser="MSIE"}else if
(a.indexOf("Firefox")>=0)...{var b=a.split("Firefox/")[1].split("."),c=parseInt(b[0]);if(c>=2)
Silverlight.ua.Browser="Firefox";else...{var d=parseInt(b[1]);if(c==1&&d>=5)Silverlight.ua.Browser="Firefox"}}else if
(a.indexOf("Safari")>=0)Silverlight.ua.Browser="Safari"};Silverlight.detectUserAgent();Silverlight.isInstalled=function(d)
...{var c=false,a=null;try...{var b=null;if(Silverlight.ua.Browser=="MSIE")b=new ActiveXObject("AgControl.AgControl");else if
(navigator.plugins["Silverlight Plug-In"])...{a=document.createElement("div");document.body.appendChild(a);a.innerHTML='<embed
type="application/x-silverlight" />';b=a.childNodes[0]}if(b.IsVersionSupported(d))c=true;b=null;Silverlight.available=true}
catch(e)...{c=false}if(a)document.body.removeChild(a);return c};Silverlight.createObject=function(l,g,m,j,k,i,h)...{var b=
...{},a=j,c=k;a.source=l;b.parentElement=g;b.id=Silverlight.HtmlAttributeEncode(m);b.width=Silverlight.HtmlAttributeEncode
(a.width);b.height=Silverlight.HtmlAttributeEncode(a.height);b.ignoreBrowserVer=Boolean
(a.ignoreBrowserVer);b.inplaceInstallPrompt=Boolean(a.inplaceInstallPrompt);var e=a.version.split(".");b.shortVer=e[0]
+"."+e[1];b.version=a.version;a.initParams=i;a.windowless=a.isWindowless;a.maxFramerate=a.framerate;for(var d in c)if(c[d]
&&d!="onLoad"&&d!="onError")...{a[d]=c[d];c[d]=null}delete a.width;delete a.height;delete a.id;delete a.onLoad;delete
a.onError;delete a.ignoreBrowserVer;delete a.inplaceInstallPrompt;delete a.version;delete a.isWindowless;delete
a.framerate;if(Silverlight.isInstalled(b.version))...{if(Silverlight._silverlightCount==0)if(window.addEventListener)
window.addEventListener("onunload",Silverlight.__cleanup,false);else window.attachEvent
("onunload",Silverlight.__cleanup);var
f=Silverlight._silverlightCount++;a.onLoad="__slLoad"+f;a.onError="__slError"+f;window[a.onLoad]=function(a)...{if(c.onLoad)
c.onLoad(document.getElementById(b.id),h,a)};window[a.onError]=function(a,b)...{if(c.onError)c.onError(a,b);else
Silverlight.default_error_handler(a,b)};slPluginHTML=Silverlight.buildHTML(b,a)}else
slPluginHTML=Silverlight.buildPromptHTML(b);if(b.parentElement)b.parentElement.innerHTML=slPluginHTML;else return
slPluginHTML};Silverlight.supportedUserAgent=function()...{var
a=Silverlight.ua,b=a.OS=="Unsupported"||a.Browser=="Unsupported"||a.OS=="Windows"&&a.Browser=="Safari"||a.OS.indexOf("Mac")
>=0&&a.Browser=="IE";return !b};Silverlight.buildHTML=function(c,d)...{var a=[],e,i,g,f,h;if(Silverlight.ua.Browser=="Safari")
...{a.push("<embed ");e="";i=" ";g='="';f='"';h=' type="application/x-silverlight"/>'+"<iframe
style='visibility:hidden;height:0;width:0'/>"}else...{a.push('<object type="application/x-silverlight"');e=">";i=' <param
name="';g='" value="';f='" />';h="</object>"}a.push(' id="'+c.id+'" width="'+c.width+'" height="'+c.height+'" '+e);for(var b
in d)if(d[b])a.push(i+Silverlight.HtmlAttributeEncode(b)+g+Silverlight.HtmlAttributeEncode(d[b])+f);a.push(h);return a.join
("")};Silverlight.default_error_handler=function(e,b)...{var d,c=b.ErrorType;d=b.ErrorCode;var a=" Silverlight error message
";a+="ErrorCode: "+d+" ";a+="ErrorType: "+c+" ";a+="Message: "+b.ErrorMessage+" ";if(c=="ParserError")
...{a+="XamlFile: "+b.xamlFile+" ";a+="Line: "+b.lineNumber+" ";a+="Position: "+b.charPosition+" "}else if
(c=="RuntimeError")...{if(b.lineNumber!=0)...{a+="Line: "+b.lineNumber+" ";a+="Position: "+b.charPosition+" "}
a+="MethodName: "+b.methodName+" "}alert(a)};Silverlight.createObjectEx=function(b)...{var
a=b,c=Silverlight.createObject(a.source,a.parentElement,a.id,a.properties,a.events,a.initParams,a.context);if
(a.parentElement==null)return c};Silverlight.buildPromptHTML=function(i)...{var
a=null,f=Silverlight.fwlinkRoot,c=Silverlight.ua.OS,b="92822",d;if(i.inplaceInstallPrompt)...{var h;if(Silverlight.available)
...{d="94376";h="94382"}else...{d="92802";h="94381"}var g="93481",e="93483";if(c=="Windows")...{b="92799";g="92803";e="92805"}else
if(c=="MacIntel")...{b="92808";g="92804";e="92806"}else if(c=="MacPPC")...{b="92807";g="92815";e="92816"}a='<table border="0"
cellpadding="0" cellspacing="0" width="205px"><tr><td><img title="Get Microsoft Silverlight"
onclick="javascript:Silverlight.followFWLink({0});" style="border:0; cursor:pointer" src="{1}"/></td></tr><tr><td
style="background:#C7C7BD; text-align: center; color: black; font-family: Verdana; font-size: 9px; padding-bottom: 0.05cm;
;padding-top: 0.05cm" >By clicking <b>Get Microsoft Silverlight</b> you accept the <a title="Silverlight License Agreement"
href="{2}" target="_top" style="text-decoration: underline; color: #36A6C6"><b>Silverlight license
agreement</b></a>.</td></tr><tr><td style="border-left-style: solid; border-right-style: solid; border-width: 2px; border-
color:#c7c7bd; background: #817d77; color: #FFFFFF; text-align: center; font-family: Verdana; font-size: 9px">Silverlight
updates automatically, <a title="Silverlight Privacy Statement" href="{3}" target="_top" style="text-decoration: underline;
color: #36A6C6"><b>learn more</b></a>.</td></tr><tr><td><img src="{4}"/></td></tr></table>';a=a.replace
("{2}",f+g);a=a.replace("{3}",f+e);a=a.replace("{4}",f+h)}else...{if(Silverlight.available)d="94377";else d="92801";if
(c=="Windows")b="92800";else if(c=="MacIntel")b="92812";else if(c=="MacPPC")b="92811";a='<div style="width: 205px; height:
67px; background-color: #FFFFFF"><img onclick="javascript:Silverlight.followFWLink({0});" style="border:0; cursor:pointer"
src="{1}" alt="Get Microsoft Silverlight"/></div>'}a=a.replace("{0}",b);a=a.replace("{1}",f+d);return
a};Silverlight.__cleanup=function()...{for(var a=Silverlight._silverlightCount-1;a>=0;a--)...{window["__slLoad"+a]=null;window
["__slError"+a]=null}if(window.removeEventListener)window.removeEventListener("unload",Silverlight.__cleanup,false);else
window.detachEvent("onunload",Silverlight.__cleanup)};Silverlight.followFWLink=function(a)
...{top.location=Silverlight.fwlinkRoot+String(a)};Silverlight.HtmlAttributeEncode=function(c)...{var a,b="";if(c==null)return
null;for(var d=0;d<c.length;d++)...{a=c.charCodeAt(d);if(a>96&&a<123||a>64&&a<91||a>43&&a<58&&a!=47||a==95)
b=b+String.fromCharCode(a);else b=b+"&#"+a+";"}return b}
Test.html(HTML頁面,也是Silverlight的最終展示頁面)
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script type="text/javascript" src="Silverlight.js"></script>
<script type="text/javascript" src="Test.html.js"></script>
<script type="text/javascript" src="Test.xaml.js"></script>
</head>
<body>
<div id="SilverlightPlugInHost">
<script type="text/javascript">...
createSilverlight();
</script>
</div>
</body>
</html>
Test.xaml(Silverlight程序主體)
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Canvas>
<!--Path1,EllipseGeometry-->
<Path Stroke="Black" StrokeThickness="2">
<Path.Data>
<EllipseGeometry x:Name="myEllipse" Center="100,100" RadiusX="50" RadiusY="50" />
</Path.Data>
<Path.Fill>
<RadialGradientBrush Center="0.5,0.5" GradientOrigin="0.15,0.3">
<GradientStop Color="LightYellow" Offset="0.1" />
<GradientStop Color="Yellow" Offset="0.3" />
<GradientStop Color="Orange" Offset="0.6" />
<GradientStop Color="Red" Offset="1.0" />
</RadialGradientBrush>
</Path.Fill>
<!--Trigger-->
<Path.Triggers>
<EventTrigger RoutedEvent="Path.Loaded">
<BeginStoryboard>
<Storyboard>
<PointAnimation Storyboard.TargetName="myEllipse"
Storyboard.TargetProperty="Center"
From="100,100" To="300,300" Duration="0:0:1.5"
RepeatBehavior="Forever"/>
<DoubleAnimation Storyboard.TargetName="myEllipse"
Storyboard.TargetProperty="RadiusX"
From="50" To="150" Duration="0:0:1.5" RepeatBehavior="Forever"/>
<DoubleAnimation Storyboard.TargetName="myEllipse"
Storyboard.TargetProperty="RadiusY"
From="50" To="150" Duration="0:0:1.5" RepeatBehavior="Forever"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Path.Triggers>
</Path>
</Canvas>
</Canvas>
Test.html.js(載入Silverlight對象)
...{
Silverlight.createObjectEx(...{
source: 'Test.xaml',
parentElement: document.getElementById('SilverlightPlugInHost'),
id: 'SilverlightPlugIn',
properties: ...{
width: '500',
height: '500',
background:'#ffffffff',
isWindowless: 'false',
version: '1.0'
},
events: ...{
//onError: null,
//onLoad: Silverlight.createDelegate(scene, scene.handleLoad)
},
context: null
});
}
if (!window.Silverlight)
window.Silverlight = ...{};
Silverlight.createDelegate = function(instance, method) ...{
return function() ...{
return method.apply(instance, arguments);
}
}
Test.xaml.js(Silverlight事件驅動代碼)
window.Animation = ...{};
Animation.Scene = function()
...{
}
Animation.Scene.prototype =
...{
handleLoad: function(control, userContext, rootElement)
...{
this.control = control;
// Sample button event hookup: Find the button and then attach event handlers
this.button = rootElement.children.getItem(0);
this.button.addEventListener("MouseEnter", Sys.Silverlight.createDelegate(this, this.handleMouseEnter));
this.button.addEventListener("MouseLeftButtonDown", Sys.Silverlight.createDelegate(this, this.handleMouseDown));
this.button.addEventListener("MouseLeftButtonUp", Sys.Silverlight.createDelegate(this, this.handleMouseUp));
this.button.addEventListener("MouseLeave", Sys.Silverlight.createDelegate(this, this.handleMouseLeave));
},
// Sample event handlers
handleMouseEnter: function(sender, eventArgs)
...{
// The following code shows how to find an element by name and call a method on it.
var mouseEnterAnimation = sender.findName("mouseEnter");
mouseEnterAnimation.begin();
},
handleMouseDown: function(sender, eventArgs)
...{
var mouseDownAnimation = sender.findName("mouseDown");
mouseDownAnimation.begin();
},
handleMouseUp: function(sender, eventArgs)
...{
var mouseUpAnimation = sender.findName("mouseUp");
mouseUpAnimation.begin();
// Put clicked logic here
alert("clicked");
},
handleMouseLeave: function(sender, eventArgs)
...{
var mouseLeaveAnimation = sender.findName("mouseLeave");
mouseLeaveAnimation.begin();
}
}