我的应用程序有大量的图像要显示,并且应该调整大小以便以固定的宽度和高度进行统一显示,为此我在图像的onload图像中编写了一个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)'>
这种方式适用于除Chrome 6,7,8之外的Chrome和Firefox。我很痛苦,我怎么能在IE 6,7,8上完成这个任务。
非常感谢。
答案 0 :(得分:1)
我首先要说的是,如果您要提供的图像以特定大小显示,您应该首先从服务器以正确的大小发送它们。发送过大的图像并让浏览器调整大小是不好的做法,因为这意味着你占用的带宽比你需要的多得多。您的用户可能会限制带宽,并且可能无法理解由此导致的页面上的额外加载时间。
但是,我真的不知道你为什么需要这样做呢?默认情况下,HTML会将图片缩放到包含它的<img>
标记的大小,因此您需要为height
指定width
和<img>
个样式标记,缩放将自动完成。绝对不需要所有那些搞乱Javascript。
<img src='PATH' style='width:100px; height:100px;'>
这应该适用于所有浏览器;不需要JS。图像应该按比例缩放。
但理想情况下,正如我所说,如果您不打算以全尺寸使用它们,请尽量避免向页面发送过大的图像。
答案 1 :(得分:1)
更改作业顺序。首先分配onload函数,然后分配src属性。它至少适用于IE 8。
var div = document.getElementById('div');
var img = new Image();
img.onload = function() {
var text = document.createTextNode('loaded ' + img.src);
div.appendChild(text);
};
window.setTimeout(function() {
var random = Math.random();
img.src ="http://stackoverflow.com/users/flair/450989.png?random=" + random;
}, 1000);
div.appendChild(img);
<div id="div"/>