本文介绍一段用于在图片加载完成后自动调整大小的 JavaScript 函数 ImgAutoSize。该函数通过比较图片原始宽高与设定的最大宽高(FitWidth, FitHeight),按比例计算新尺寸,确保图片在指定容器内显示且不变形。同时包含点击放大查看原图的功能。
// 方案:setSelectReadOnly 用于设定极select控件ReadOnly,
// 此为一个模拟只读而非真正的只读
// 调用了onbeforeactivate,onfocus,onmouseover,onmouseout事件
图片自动缩放实现原理
// 示例:< img src='img.jpg' onload='ImgAutoSize(ImgD,FitWidth,FitHeight)' > ;
// 创建者:sl
// ---------------------------------------------------
ImgAutoSize 函数代码详解
function ImgAutoSize(imgD,FitWidth,FitHeight)
{
var image1=new Image();
image1.onload = function ()
{
if(this.width>0 && this.height>0)
{
if(this.width/this.height>= FitWidth/FitHeight)
{
if(this.width>FitWidth)
{
imgD.width=FitWidth;
imgD.height=(this.height*FitWidth)/this.width;
}
else
{
imgD.width=this.width;
imgD.height=this.height;
}
}
else
{
if(this.height>FitHeight)
{
imgD.height=FitHeight;
imgD.width=(this.width*FitHeight)/this.height;
}
else
{
imgD.width=this.width;
imgD.height=this.height;
}
}
}
image1 = null;
}
image1.src=imgD.src;
imgD.style.cursor = 'hand';
imgD.onclick= function(){openWin(this.src,'imgphoto',600,400)};
imgD.title = "点击在新窗口中查看原图";
}