前段时间一直搞活动页面,趁着有空闲的时间总结下as跟js之间的交互。
首先来段as的代码。
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.external.ExternalInterface;
public class TestAs extends MovieClip {
public function TestAs() {
bindAllEvent();
init();
}
private function init():void{
btn1.label = "按我吧";
ExternalInterface.addCallback("callASMethod", callASMethod);
}
private function bindAllEvent():void{
btn1.addEventListener("click", btn1Handler);
}
private function btn1Handler(event:Event):void{
callJSMethod();
}
//js调用as
private function callASMethod(value:String):void{
btn1.label = value;
}
//as调用js代码
private function callJSMethod():void{
ExternalInterface.call("callJSMethod", "测试下");
}
}
}
代码很简单,上面只有一个按钮btn1,定义了两个方法,主要用来给js跟as交互的。
页面代码:
<html> <head> <title>as与js交互</title> </head> <body> <input type="button" value="调用flash方法" οnclick="sendToAS()"/> <div id="swfcontent"></div> <script type="text/javascript"> function insertFlash(elm, eleid, url, w, h, b) { if (!document.getElementById(elm)) return; var str = ''; str += '<object width="' + w + '" height="' + h + '" id="' + eleid + '" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0">'; str += '<param name="movie" value="' + url + '" />'; str += '<param name="allowScriptAccess" value="always" />'; str += '<param name="base" value="' + b + '" />'; str += '<param name="wmode" value="transparent" />'; str += '<param name="quality" value="autohigh" />'; str += '<embed width="' + w + '" base="' + b + '" height="' + h + '" name="' + eleid + '" src="' + url + '" quality="autohigh" swLiveConnect="always" wmode="transparent" allowScriptAccess="always" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>'; str += '</object>'; document.getElementById(elm).innerHTML = str } var base = "";//指针及抽奖图片背景所在路径 insertFlash("swfcontent", "Lottery", "1.swf", 500, 400, base); //as调用js方法 function callJSMethod(msg){ alert(msg); } function getMovie(movieName) { if (navigator.appName.indexOf("Microsoft") != -1) { return window[movieName]; } else { return document[movieName]; } } //js调用as方法 function sendToAS() { getMovie("Lottery").callASMethod("js调用flash"); } </script> </body> </html>
flash跟页面各有一个按钮,html页面的按钮点击后会访问as上的方法,而flash上按钮点击后会调用js上的方法。