图片处理函数

01
//图片加载完成后按最大宽高等比缩放
02
function resize(o,mw,mh){
03
    var ow=o.width,oh=o.height,os=ow/oh,w=mw||100,h=mh||100,s=w/h;
04
    o.setAttribute('oldheight',oh)
05
    if(os>s){
06
        if(ow>w){
07
            o.width=w;o.height=w/os;
08
        }
09
    }else{
10
        if(oh>h){
11
            o.height=h;o.width=h*os
12
        }
13
    }
14
    if(o.height<h){
15
        o.style.marginTop=(h-o.height)/2+'px'
16
    }
17
}
18
//图片加载出错时替换成默认图片,同时也解决了ie6的over stack问题
19
function errorload(o,src,mw,mh){
20
    var w=mw||100,h=mh||100;
21
    var img=new Image();
22
    img.src=src;
23
    img.width=w;
24
    img.height=h;
25
    o.parentNode.replaceChild(img, o)
26
}

//使用时直接在img标签内写上
<
img src="原始图片路径" onload="resize(this,最大宽,最大高)" onerror="errorload(this,'默认图片路径',最大宽,最大高)" alt="*" />
原文地址:https://www.cnblogs.com/zgzy/p/3070513.html