JavaScript 实现图片加载时自动按比例缩放
本文介绍一段用于在图片加载完成后自动调整大小的 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 = "点击在新窗口中查看原图";
}
JS运算符优先级与结合性的区别是什么?
2026-11-05 13:22:02
JS Map怎么只遍历Key或Value
2026-11-05 13:00:36
D3.js 与 ECharts 选型对比:灵活性 vs 开发效率
2026-11-05 09:45:01
为什么JS中typeof []返回object:数组类型检测误区解析
2026-11-04 19:50:47
D3.js 新手入门:环境搭建与第一个条形图实现
2026-11-04 10:49:48
