JS动态加载图片

      如下js可以载入一个还没有在页面中的图片,并且可以获得其高度和宽度:

function  EnhancedImage(src,onLoaded){
    
var  self  =   this ;
    
this .src  =  src;
    
this .width  =   0 ;
    
this .height  =   0 ;
    
this .onLoaded  =  onLoaded;
    
this .loaded  =   false ;
    
this .image  =   null ;
    
    
this .load  =   function (){
        
if ( this .loaded)
            
return ;
        
this .image  =   new  Image();
        
this .image.src  =   this .src;
        
function  loadImage(){
            
if (self.width  !=   0   &&  self.height  !=   0 ){
                clearInterval(interval);
                self.loaded 
=   true ;
                self.onLoaded(self);
// 将实例传入回调函数
            }
            self.width 
=  self.image.width; // 是number类型
            self.height  =  self.image.height;
        }
        
var  interval  =  setInterval(loadImage, 100 );
    }
}

      总的原理就是new一个Image对象,设置了src属性过后,不断的检查需要载入的图片的宽和高,如果载入图片成功的话,宽和高都是不为0的数值,这个时候停止Interval ,并且执行onLoaded。

      这段js代码的使用方法:

var  img  =   new  EnhancedImage( " http://www.google.cn/intl/zh-CN/images/logo_cn.gif " ,onImageLoad);
function  onImageLoad(image){
    document.body.appendChild(image.image);
    alert(
" image loaded and the size is  "   +  image.width  +   " * "   +  image.height);
}

function  Button1_onclick() {
    img.load();
}

 

 

转载于:https://www.cnblogs.com/LongWay/archive/2008/10/15/1311293.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值