【发布时间】:2013-12-19 09:21:55
【问题描述】:
我的应用程序要呈现大量图像,并且应该调整其大小以便以固定的宽度和高度统一呈现,为此我在图像的加载图像中编写了一个 JavaScript 方法,如下所示:
var autoResizeImage = function(targetWidth, targetHeight, objImg) {
if (0 >= targetWidth || 0 >= targetHeight) {
// Ilegal parameters, just return.
return;
}
var img = new Image();
img.src = objImg.src;
// Calculate the width and height immediately the image is loaded.
img.onload = function() {
var hRatio;
var wRatio;
var width = img.width;
var height = img.height;
var calcWidth = width;
var calcHeight = height;
wRatio = targetWidth / width;
hRatio = targetHeight / height;
if (wRatio < hRatio) {
calcHeight = targetHeight;
calcWidth = (targetHeight / height) * width;
} else {
calcWidth = targetWidth;
calcHeight = (targetWidth / width) * height;
}
objImg.width = calcWidth;
objImg.height = calcHeight;
};
};
HTML 图像:
<img src='PATH' onload='autoResizeImage(100, 100, this)'>
这种方式适用于除 IE 6、7、8 之外的 Chrome 和 Firefox。我为此受苦,如何在 IE 6、7、8 上完成此任务。
非常感谢。
【问题讨论】:
-
在设置源之前添加onload函数。已回复here
标签: javascript image internet-explorer google-chrome onload