Blog Source http://blog.csdn.net/eduxh/article/details/1906246
//Image self-adapting size
//ID of the IMG control
//Width and height are the wide height of the IMG parent control-that is, the maximum width and height of the img
//Example: "
functionImgfit (Id,width,height)
{
VarImagearr=document.getElementById (ID);
If(Imagearr.offsetwidth>Width||Imagearr.offsetheight>Height
{
ImageRate1=parseint (Imagearr.offsetwidth)/Width
ImageRate2=parseint (Imagearr.offsetheight)/Height
If(ImageRate2>IMAGERATE1)
ImageArr.style.height=Imagearr.offsetheight/imageRate2+"px";
Else
ImageArr.style.width = imagearr.offsetwidth/imageRate1 +"px";
}
}
To add a center handle:
functionImgfit (Imagearr,width,height)
{
//var Imagearr=document.getelementbyid (ID);
//if (Imagearr.offsetwidth>width | | imagearr.offsetheight>height)
//{
//alert (IMAGEARR.STYLE.MARGINTOP);
Swidth=Imagearr.offsetwidth;
Sheight=Imagearr.offsetheight;
ImageRate1=parseint (Imagearr.offsetwidth)/Width
ImageRate2=parseint (Imagearr.offsetheight)/Height
If(ImageRate2>IMAGERATE1)
{
ImageArr.style.height=Sheight/ImageRate2+"Px";
ImageArr.style.marginLeft=(width-Swidth/IMAGERATE2)/2+"Px";
}
Else
{
ImageArr.style.width=Swidth/ImageRate1+"Px";
ImageArr.style.marginTop=(Height-sheight/imagerate1) /2+ "px" }   
//alert ( imagearr.offsetwidth+ ":" +imagearr.offsetheight);
//}
}
JavaScript automatically adapts to picture size