=波波日志 > flash/flex/fcs/AIR > As+lightbox+js实现实时加载图片进度=

As+lightbox+js实现实时加载图片进度

  不久前在csdn的js板块看到一个as+js+lightbox动态加载图片显示进度的程序,随便帮改了下代码。后面要帮女朋友搞她设计作品的展示时发现代码中的flash只提供了成功加载时的回调函数,而如果图片未找到或者刚开始加载时没有什么提示。所以自己把swf反编译了一下,修改了as脚本,使之拥有了4个回调,加载图片开始,过程,成功加载和错误的回调,增强下用户体验O(∩_∩)O~

  示例代码点击此下载

  效果查看

  效果如下



  
  下面列出as脚本,js脚本的主要代码供大家学习下。lightbox效果已经继承到了design.js文件里面了。


  as脚本部分,loadSwf.fla第一帧的脚本

+展开
-ActionScript
//loadUrl:要加载的图片地址URL
//loading:加载过程反馈信息的js函数名 ,参数 function(p:完成百分比,loaded:已经加载的,total:总大小) 
///Success:成功加载完成后执行的js函数名,参数 function(w:图片原始长度,h:图片原始宽)
//Failure:加载失败执行的函数名称,参数 function(msg:错误信息)
function loadPicture(loadUrl,loading,Success,Failure)
{
    var _loc2 = random(1000000000);
    _root.createEmptyMovieClip("loadMc" + _loc2, _root.getNextHighestDepth());
//这里flash使用了一个类as.loadPic,在下面贴出代码
    new as.loadPic(_root["loadMc" + _loc2], loadUrl
function (ob){//成功时调用js传递进来的js回调函数,下面同理
        new flash.external.ExternalInterface.call(Success,loadUrl, ob._width, ob._height);
    }
function (loadN,loaded,total){//过程
        new flash.external.ExternalInterface.call(loading, loadN, loaded,total);
    }
function (err){//发生错误
        new flash.external.ExternalInterface.call(Failure,err);
    });
// End of the function
//使用flash.external.ExternalInterface接口注册给js调用的函数
flash.external.ExternalInterface.addCallback("forJS"null, loadPicture);


loadPic.as源代码
+展开
-ActionScript
class as.loadPic{
    function loadPic(ob, uri,Success, loadIng,Failure){
        if (ob && uri){
            var _loc2 = new MovieClipLoader();
            var _loc1 = new Object();
            var loadnum;
            _loc1.onLoadStart = function (tmc){
            };
            _loc1.onLoadProgress = function (tmc, loadedBytes, totalBytes){
                loadnum = int(loadedBytes / totalBytes * 100);
                loadIng(loadnum,loadedBytes,totalBytes);
            };
            _loc1.onLoadComplete = function (tmc){
            };
            _loc1.onLoadInit = function (tmc){
                if (Success && typeof(Success) == "function")Success(tmc);
            };
            _loc1.onLoadError = function (tmc, errc){
                if (Failure && typeof(Failure) == "function")Failure(errc);
            };
            _loc2.addListener(_loc1);
            _loc2.loadClip(uri, ob);
        } 
    } 
}



design.js源代码
+展开
-JavaScript
var Showbo={author:'Showbo'};
Showbo.IsIE=!!document.all;
//带小数位的舍入
//页面的高和宽******************************
Showbo.isStrict=document.compatMode == "CSS1Compat";
Showbo.BodyScale={x:0,y:0,tx:0,ty:0};//(x,y):当前的body显示大小  (tx,ty):总的页面滚动宽度和高度【包括原始的】
Showbo.getClientHeight=function(){return Showbo.isStrict ? document.documentElement.clientHeight :document.body.clientHeight;}
Showbo.getScrollHeight=function(){var h=!Showbo.isStrict?document.body.scrollHeight:document.documentElement.scrollHeight;return Math.max(h,this.getClientHeight());}
Showbo.getHeight=function(full){return full?this.getScrollHeight():this.getClientHeight();}
Showbo.getClientWidth=function(){return Showbo.isStrict?document.documentElement.clientWidth:document.body.clientWidth;}
Showbo.getScrollWidth=function(){var w=!Showbo.isStrict?document.body.scrollWidth:document.documentElement.scrollWidth;return Math.max(w,this.getClientWidth());}
Showbo.getWidth=function(full){return full?this.getScrollWidth():this.getClientWidth();}
Showbo.initBodyScale=function(IsSource){Showbo.BodyScale.x=Showbo.getWidth(false);Showbo.BodyScale.y=Showbo.getHeight(false);Showbo.BodyScale.tx=Showbo.getWidth(true);Showbo.BodyScale.ty=Showbo.getHeight(true);if(IsSource){Showbo.BodyScale.otx=Showbo.getWidth(true);Showbo.BodyScale.oty=Showbo.getHeight(true);/*获取原始的高和宽*/}}
//页面的高和宽******************************
Showbo.round=function(num,radixNum){var t=Math.pow(10,radixNum);return Math.round(num*Math.pow(10,radixNum))/t;}
Showbo.$=function(Id,isFrame){var o;if("string"==typeof(Id))o= document.getElementById(Id);else if("object"==typeof(Id))o= Id;else return null;return isFrame?(Showbo.IsIE?frames[Id]:o.contentWindow):o;}
Showbo.$s=function(){var o,tag;if(arguments.length==1){o=document;tag=arguments[0];}else{o=arguments[0];tag=arguments[1];}return o.getElementsByTagName(tag);}
Showbo.Design={
    lightBox:null,
    dvPopDesign:null,
    tool:null,
    dvpic:null,
    loading:null,
    dvpro:null,
    dvinfo:null,
    newA:null,
    step:100,
    min:300,
    pos:{x:0,y:0,ex:0,ey:0,drag:false},
    /*Flash中调用的js函数*/
    Start:function(){//开始
      this.dvpro.style.width="1%";
  this.dvinfo.innerHTML="准备下载,请等待...";
    },
    Loading:function(p,loaded,total){//加载进度
      this.dvpro.style.width=p+"%";
  this.dvinfo.innerHTML="已下载:"+Showbo.round(loaded/1024,1)+"kb,总共"+Showbo.round(total/1024,1)+"kb,完成"+p+'%';
    },
    Success:function(picurl,w,h){//成功加载,不过测试时bmp不能取到w和h参数,汗。。。  
      this.loading.style.display='none';
      this.dvpic.parentNode.style.display=this.tool.style.display='block';
      this.dvpic.src=picurl;
      this.newA.href=picurl;
      var me=this;
      setTimeout(function(){me.Org();},200);//需要延时执行,即使缓存了图片也会有一定的加载时间,不延时有些时候取不到实际的值
    },
    Failure:function(msg){//发生错误时的回调函数,msg为flash中传出的,只有URLNotFound,LoadNeverCompleted
      //URLNotFound:找不到文件或者服务器关闭----当服务器关闭或找不到文件时
      //LoadNeverCompleted:当下载由于服务器超载、服务器崩溃等原因中断时。
      this.dvinfo.innerHTML='<font color="red">'+msg+'</font> <a href="javascript:Showbo.Design.hide();">关闭</a>';
    },
    JScallSWF:function(picurl){ //js调用flash中的方法,默认名为forJS
       if(window["swfId"]&&window["swfId"].forJS)window["swfId"].forJS(picurl,'Showbo.Design.Loading','Showbo.Design.Success','Showbo.Design.Failure');//ie
       else if(Showbo.$("swfId").forJS)Showbo.$("swfId").forJS(picurl,'Showbo.Design.Loading','Showbo.Design.Success','Showbo.Design.Failure');
   else if(document["swfId"]&&document["swfId"].forJS)document["swfId"].forJS(picurl,'Showbo.Design.Loading','Showbo.Design.Success','Showbo.Design.Failure');//ff
    },
    Org:function(){
      this.dvpic.style.cssText="";//移除所有样式,不要使用removeAttribu("style"),在ie6下速度奇慢
      this.dvPopDesign.style.height=this.dvPopDesign.style.width='auto';
      this.onResize();
    },
    Drag:function(e){//拖动的处理函数
      Showbo.Design.cancelEvent(e);
      e=e||event;
      if((Showbo.IsIE&&e.button!=1)||(!Showbo.IsIE&&e.button!=0))return false;
      if(e.type.indexOf('mousedown')!=-1){//拖拽开始
        if(Showbo.IsIE)this.setCapture();//在ie下调用setCapture,ff下就算window.captureEvents当移除body显示范围也不会释放对象。
        Showbo.Design.pos.x=parseInt(Showbo.Design.dvPopDesign.style.left,10);
        Showbo.Design.pos.y=parseInt(Showbo.Design.dvPopDesign.style.top,10);
        Showbo.Design.pos.ex=e.clientX;
        Showbo.Design.pos.ey=e.clientY;
        Showbo.Design.pos.drag=true;
      }
      else if(e.type.indexOf('mousemove')!=-1){//拖拽过程
        if(Showbo.Design.pos.drag){
          Showbo.Design.dvPopDesign.style.left=Showbo.Design.pos.x+e.clientX-Showbo.Design.pos.ex+'px';
          Showbo.Design.dvPopDesign.style.top=Showbo.Design.pos.y+e.clientY-Showbo.Design.pos.ey+'px';          
        }
      }
      else if(e.type.indexOf('mouseup')!=-1){//拖拽结束
       if(Showbo.IsIE)this.releaseCapture();
        Showbo.Design.onResize();//重新设定位置,注意这句要放到下面这句上面,要不onResize会重新设置图片层位置
        Showbo.Design.pos.drag=false;
      }
    },
    mouseWheel:function(e){//鼠标在图片上使用滚轮时的处理函数
      Showbo.Design.cancelEvent(e);
      e=e||event;
      var w=this.offsetWidth,h=this.offsetHeight,refH=Showbo.Design.step*h/w;
      if((Showbo.IsIE&&e.wheelDelta<0)||(!Showbo.IsIE&&e.detail>0)){//往下扩大
       // if(this.offsetWidth<Showbo.Design.w){
           this.style.width=w+Showbo.Design.step+'px';
           this.style.height=h+refH+'px';
           Showbo.Design.dvPopDesign.style.width=this.offsetWidth+'px';
       // }
      }else{//缩小
         if(w-Showbo.Design.step>=Showbo.Design.min){
           this.style.width=w-Showbo.Design.step+'px';
           this.style.height=h-refH+'px';
           Showbo.Design.dvPopDesign.style.width=this.offsetWidth+'px';
         }
      }
     Showbo.Design.onResize();
    },
    documentMouseWheel:function(e,IsTimer){//在body上使用鼠标滚轮时,如果图片当前高度小于body的显示高度则移动显示图片的层
       var me=Showbo.Design,ds=me.dvPopDesign;
       if(!IsTimer)setTimeout(function(){me.documentMouseWheel(null,true)},100);
       else if(ds.offsetHeight'px';
    },
    InitDesign:function(){//需要手动调用此方法,要不ie下使用append增加的flash不能调用其方法,奇怪。。。
      var html='<p id="designTools"><a href="#" title="在新窗口中打开" target="_blank"></a><a class="just"  href="javascript:Showbo.Design.Org()" title="实际大小"></a>'
        +'<a class="close" title="关闭" href="javascript:Showbo.Design.hide()"></a><span>鼠标滚动缩放图片,按下左键拖动</span></p>'
        +'<div class="pic"><img  id="designPic"/></div>'+
        '<div class="loading" id="designLoading"><div class="pro" id="designPro"></div><div id="designInfo"></div></div>';
      document.write('<div class="popdesign" id="dvPopDesign">'+html+'</div>');
      this.dvPopDesign=Showbo.$('dvPopDesign');
      document.write('<div id="ShowBolightBox"></div>');
      this.lightBox=Showbo.$('ShowBolightBox');
      this.tool=Showbo.$('designTools');
      this.newA=Showbo.$s(this.tool,'a')[0];
      this.dvpic=Showbo.$('designPic');
      this.dvpic.onmousedown=this.dvpic.onmousemove=this.dvpic.onmouseup=this.Drag;
      if(Showbo.IsIE)this.dvpic.onmousewheel=this.mouseWheel;
      else this.dvpic.addEventListener('DOMMouseScroll',this.mouseWheel,false);
      this.loading=Showbo.$('designLoading');
      this.dvpro=Showbo.$('designPro');
      this.dvinfo=Showbo.$('designInfo');
      document.write('<div class="myloadswf">');
      document.write(Showbo.IsIE?'<object id=swfId classid=clsid:D27CDB6E-AE6D-11cf-96B8-444553540000><param name="src" value="images/loadSwf.swf"></object>':
                    '<embed id="swfId" type="application/x-shockwave-flash" src="images/loadSwf.swf"/>');
      document.write('</div>');
    },
    checkDOMLast:function(){//此方法非常关键,要不无法显示弹出窗口。两个对象dvPopDesign和lightBox必须处在body的最后两个节点内
      if(document.body.lastChild!=this.lightBox){
        document.body.appendChild(this.dvPopDesign);
        document.body.appendChild(this.lightBox);
      }
    },
    show:function(picurl,e){//显示图片
      this.checkDOMLast();//检查是否在最后     
      this.lightBox.style.display=this.dvPopDesign.style.display='block';
      this.dvpic.parentNode.style.display=this.tool.style.display='none';
      this.dvpic.src='';
      this.loading.style.display='block';
      this.dvPopDesign.style.height=this.dvPopDesign.style.width='auto';
      this.onResize();
      this.JScallSWF(picurl);//调用flash提供的方法
      this.Start();
      this.cancelEvent();
      var me=this;
      //添加事件
      if(Showbo.IsIE)document.documentElement.onmousewheel=this.documentMouseWheel;
      else document.documentElement.addEventListener('DOMMouseScroll',this.documentMouseWheel,false);
    },
    cancelEvent:function(e){//取消默认事件
      if(e){//w3c浏览器
        e.stopPropagation();
        e.preventDefault();        
      }
      else if(window.event){//ie浏览器
       window.event.returnValue=false;window.event.cancelBubble=true;
      }
    },
    hide:function(){//隐藏
      if(!this.dvPopDesign)return false;
      //移除事件
      if(Showbo.IsIE)document.documentElement.onmousewheel=null;//ie下使用detach取消不了事件,。。。,设置为null可以。。。
      else document.documentElement.removeEventListener('DOMMouseScroll',this.documentMouseWheel,false);
      this.dvPopDesign.style.display='none';
      this.lightBox.style.display='none';
    },
    onResize:function(){//图片拖拽,鼠标滚动后重新设置lightbox和显示图片的层的位置
       Showbo.initBodyScale(); //重新初始化页面的范围
       var ds=Showbo.Design.dvPopDesign,lbox=Showbo.Design.lightBox,oL,oH,scrollTop=document.documentElement.scrollTop;
       oL=ds.offsetWidth;oH=ds.offsetHeight;
       if(!Showbo.Design.pos.drag){//不是拖动时设置图片层的left和top属性
        ds.style.left=oL>Showbo.BodyScale.otx?0:Math.floor((Showbo.BodyScale.x-ds.offsetWidth)/2)+'px';
        ds.style.top=scrollTop+(oH>Showbo.BodyScale.oty?0:Math.floor((Showbo.BodyScale.y-ds.offsetHeight)/2))+'px';
       }else{
         oL+=(ds.style.left?parseInt(ds.style.left):0);
         oH+=(ds.style.top?parseInt(ds.style.top):0);
       }
       Showbo.Design.lightBox.style.width=(oL'px';
       Showbo.Design.lightBox.style.height=(oH'px';   
    }
}



widget.css样式表
+展开
-CSS
#ShowBolightBox{display:none;-moz-opacity:0.5;filter:alpha(opacity=50);opacity:0.5;background-color:#000000;z-index:100;position:absolute;left:0px;top:0px;}
.popdesign{position:absolute;color:#999999;padding:5px 10px 10px 10px;z-index:999;background:#ffffff;font-size:12px;display:none;}
.popdesign p{margin:0px;padding:0px;display:none;}
.popdesign p a{float:left;background:transparent url(../images/imgzoom.gif) no-repeat 0px 0px;width:17px;height:17px;margin:5px;}
.popdesign p a:hover{background-position:0px -39px;}
.popdesign p a.just{background-position:-40px -0px;}
.popdesign p a.just:hover{background-position:-40px -39px;}
.popdesign p a.close{background-position:-80px -0px;}
.popdesign p a.close:hover{background-position:-80px -39px;}
.popdesign p span{float:left;margin:8px auto auto 20px;}
.popdesign div.pic{clear:both;display:none;}
.popdesign div.pic img{cursor:move;}
.popdesign div.loading{margin:40px;width:300px;display:block;}
.popdesign div.loading .pro{height:10px;width:1%;background:#ff0000;line-height:10px;overflow:hidden;}
.myloadswf{position:absolute;left:200px;top:1px;height:1px;width:1px;overflow:hidden;line-height:1px;z-index:-2;}
.myloadswf object,.myloadswf embed{width:1px;height:1px;}



测试页面index.html
+展开
-HTML
<!!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
   <meta http-equiv="content-type" content="text/html;charset=utf-8" />
   <title>编程设计网--设计作品</title>
   <meta id="metaKey" name="Keywords" content="平面设计,网页设计,的士广告,单页宣传,户外广告" />
   <meta id="metaDes" name="Description" content="平面设计,网页设计,平面设计,网页设计,的士广告,单页宣传,户外广告" />
   <link href="css/widget.css" type="text/css" rel="Stylesheet" />
   <script type="text/javascript" src="js/design.js"></script> 
</head>
<body>
    <img title="点击查看大图" src="1_s.gif" onclick="Showbo.Design.show('1.gif')" /><br >
    <img title="点击查看大图" src="2_s.jpg" onclick="Showbo.Design.show('2.jpg')" /><br ><br >
   <br ><br ><br > 这张图片特意传递错误的地址,测试错误回调函数<br >
    <img title="点击查看大图" src="1_s.gif" onclick="Showbo.Design.show('错误的图片地址.gif',event)" /><br >
    <script type="text/javascript">Showbo.Design.InitDesign();//这里需要手动调用初始化函数,要不在ie6下不能调用flash中的方法,郁闷ing....</script> 
</body>
</html>
<script type="text/javascript">
Showbo.initBodyScale(true);
</script> 
类别:flash/flex/fcs/AIR 作者:波波 日期:2009-06-26 【评论:0 阅读:】 
 
暂时没有评论!
发表留言
  • *昵称:
  • 头像:
  • 电子邮件: [留下您的邮件,方便管理员回复您。]
  • 个人网站: *验证码:
声明:本网站尊重并保护知识产权,根据《信息网络传播权保护条例》,如果我们转载或引用的作品侵犯了您的权利,请通知我们,我们会及时删除!
Powered by showbo,G51人力资讯网桂ICP备05005887号