【问题标题】:IE 6,7,8 don't support onload event in image object or DOMIE 6,7,8 不支持图像对象或 DOM 中的 onload 事件
【发布时间】: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


【解决方案1】:

我首先要说的是,如果您要以特定尺寸显示图像,您应该首先以正确的尺寸从服务器发送它们。发送过大的图像并让浏览器调整它们的大小是不好的做法,因为这意味着您使用的带宽比您需要的多得多。您的用户可能受限于带宽,并且可能不喜欢由此导致的页面上的额外加载时间。

但是,我真的不知道您为什么需要进行这种调整大小的练习?默认情况下,HTML 会将图像缩放到包含它的 &lt;img&gt; 标签的大小,因此您需要做的就是为您的 &lt;img&gt; 标签指定 heightwidth 样式,然后缩放将完成自动地。绝对没有必要用 Javascript 来搞乱。

<img src='PATH' style='width:100px; height:100px;'>

这应该适用于所有浏览器;不需要 JS。应该为您缩放图像。

但理想情况下,正如我所说,如果您不打算以全尺寸使用它们,请尽量避免向页面发送过大的图像。

【讨论】:

    【解决方案2】:

    更改作业顺序。首先分配 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);
    &lt;div id="div"/&gt;

    【讨论】:

      猜你喜欢
      • 2010-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-23
      • 2016-10-13
      • 2011-12-04
      • 1970-01-01
      相关资源
      最近更新 更多