前段时间一直搞活动页面,趁着有空闲的时间总结下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方法" onclick="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上的方法。
本文介绍了一个简单的AS(Adobe Flash)与JS(JavaScript)交互的例子。通过一个包含按钮的Flash应用和一个HTML页面,演示了如何从JavaScript调用ActionScript方法以及反过来的操作。此交互涉及到允许脚本访问设置、使用`ExternalInterface`类进行方法调用。
1362

被折叠的 条评论
为什么被折叠?



