Javascript 代码片段 - 按原始比例显示图片
function AutoSize(img, imgWidth, imgHeight)
{
var newImg = document.createElement("img");
newImg.src = img.src;
var width = newImg.width;
var height = newImg.height;
var proportion = width / height;
var wp = width / imgWidth;
var hp = height / imgHeight;
if(wp > 1 || hp > 1)
{
if(wp > hp)
{
width = imgWidth;
height = imgWidth / proportion;
}
else
{
width = imgHeight * proportion;
height = imgHeight;
}
}
img.style.width = width;
img.style.height = height;
}
{
var newImg = document.createElement("img");
newImg.src = img.src;
var width = newImg.width;
var height = newImg.height;
var proportion = width / height;
var wp = width / imgWidth;
var hp = height / imgHeight;
if(wp > 1 || hp > 1)
{
if(wp > hp)
{
width = imgWidth;
height = imgWidth / proportion;
}
else
{
width = imgHeight * proportion;
height = imgHeight;
}
}
img.style.width = width;
img.style.height = height;
}
备注:用 document.createElement("img") 方法创建新图片可以避免图片被指定尺寸后无法取得图片的真实高度、宽度,确保图片尺寸未被指定的情况下可以省略。