在flash里实现验证码功能

环境,as3.0+html

新建flash文件,在第一贞编写如下代码:

/*
初始化验证码
*/

function getCode():String
{
var code :String = "";
var codeLength:uint = 4;//验证码的长度
var selectChar:Array = new Array(1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z');//所有候选组成验证码的字符,当然也可以用中文的

var i:uint=0;
for(i=0;i<codeLength;i++)
{
   var charIndex = Math.floor(Math.random()*34);
   code += selectChar[charIndex];
}

return code;
}

/*
初始化文本
*/
var txt:TextField=new TextField();
txt.x=5;
txt.y=5;
txt.textColor=0xFFFFFF;
txt.height=20;
txt.width=50;
txt.htmlText="<FONT FACE='Times New Roman' SIZE='20' COLOR='#FFFFFF'>"+getCode()+"</FONT>";
txt.autoSize=TextFieldAutoSize.CENTER;
addChild(txt);
trace(txt.autoSize,txt.height,txt.width);
/*
移动
*/
var interval:uint=100;
var repeat:uint=0;
var right:Boolean=true;
var down:Boolean=true;
var myTimer:Timer=new Timer(interval,repeat);
myTimer.addEventListener(TimerEvent.TIMER,timerHandler);
myTimer.start();
function timerHandler(e:TimerEvent):void
{  
//左右移动
if(right)
{
   txt.x+=1;
}else
{
   txt.x-=1;
}

if(txt.x+txt.width >= stage.stageWidth)
{
   right=false;
}

if(txt.x <=0)
{
   right=true;
}
//上下移动
if(down)
{
   txt.y+=1;
}else
{
   txt.y-=1;
}

if(txt.y+txt.height >= stage.stageHeight)
{
   down=false;
}

if(txt.y <= 0)
{
   down=true;
}
}
/*
与javascript交互
*/

ExternalInterface.call("getCode",txt.text);
ExternalInterface.addCallback("flushCode",flushCode);

function flushCode()
{
txt.htmlText="<FONT FACE='Times New Roman' SIZE='20' COLOR='#FFFFFF'>"+getCode()+"</FONT>";
ExternalInterface.call("getCode",txt.text);
}

编写html代码如下:

<html>
<head>

<script>

//搭建js与flash互通的环境
function thisMovie(movieName) {

//alert(navigator.appName + " : " + navigator.appName.indexOf("Microsoft"));

if (navigator.appName.indexOf("Microsoft") != -1) {
    return window[movieName]
}else{
    return document[movieName]
}
}

//开始调用flash
function callFlash(){
thisMovie("myFlash").flushCode();
}
var flashCode;
//提供给flash调用
function getCode(code){
flashCode=code;
}
//验证
function validate(code){
if(flashCode.toLowerCase() == code.toLowerCase()){
   alert("OK");
}else{
   alert("FAIL");
}
}


</script>

</head>
<body>
<input type="text" size="6" onblur="validate(this.value)"/>
<object id="myFlash" width="80" height="35"
classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0">
<param name="movie" value="code.swf" />
<param name="quality" value="high">
<embed src="code.swf" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="80" height="35"></embed>
</object>
<a onclick="callFlash()">看不清</a>

<br/>

</body>
</html>

posted @ 2012-12-03 14:20  chinaifne  阅读(512)  评论(0编辑  收藏  举报