javascript 在 IE 上获取图像加载的图像宽度失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4472086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 13:47:44  来源:igfitidea点击:

Getting image width on image load fails on IE

javascriptimageimage-loading

提问by Fatih Acet

I have a image resizer function that resize images proportional. On every image load a call this function with image and resize if its width or height is bigger than my max width and max height. I can get img.width and img.height in FF Chrome Opera Safari but IE fails. How can i handle this?

我有一个图像调整器功能,可以按比例调整图像大小。在每个图像加载时,如果图像的宽度或高度大于我的最大宽度和最大高度,则使用图像调用此函数并调整大小。我可以在 FF Chrome Opera Safari 中获取 img.width 和 img.height,但 IE 失败。我该如何处理?

Let me explain with a piece of code.

让我用一段代码来解释。

<img src="images/img01.png" onload="window.onImageLoad(this, 120, 120)" />

function onImageLoad(img, maxWidth, maxHeight) {
     var width = img.width; // Problem is in here
     var height = img.height // Problem is in here
}

In my highligted lines img.width don't work on IE series.

在我突出显示的行中 img.width 不适用于 IE 系列。

Any suggestion?

有什么建议吗?

Thanks.

谢谢。

回答by izb

Don't use widthand height. Use naturalWidthand naturalHeightinstead. These provide the image unscaled pixel dimensions from the image file and will work across browsers.

不要使用widthheight。使用naturalWidthnaturalHeight代替。这些提供了来自图像文件的未缩放的图像像素尺寸,并且可以跨浏览器工作。

回答by m4js7er

Man, I was looking for this for 2 days. Thanks.

伙计,我一直在寻找这个2天。谢谢。

I'm using jQuery, but it doesnt matter. Problem is related to javascript in IE.

我正在使用 jQuery,但这并不重要。问题与 IE 中的 javascript 有关。

My previous code:

我之前的代码:

var parentItem = $('<div/>')
   .hide();      // sets display to 'none'

var childImage = $('<img/>')
   .attr("src", src)
   .appendTo(parentItem)   // sets parent to image
   .load(function(){
      alert(this.width);  // at this point image is not displayed, because parents display parameter is set to 'none' - IE gives you value '0'
   });

This is working in FF, Opera and Safari but no IE. I was getting '0' in IE.

这适用于 FF、Opera 和 Safari,但不适用于 IE。我在 IE 中得到“0”。

Workaround for me:

我的解决方法:

var parentItem = $('<div/>')
   .hide();

var childImage = $('<img/>')
   .attr("src", src)
   .load(function(){
      alert(this.width);  // at this point image css display is NOT 'none'  - IE gives you correct value
      childImage.appendTo(parentItem);   // sets parent to image
   });

回答by Thomas Hartvig

This is how I solved it (because it's the only js on the site I didn't want to use a library).

这就是我解决它的方法(因为它是我不想使用库的站点上唯一的 js)。

    var imageElement = document.createElement('img');
    imageElement.src = el.href; // taken from a link cuz I want it to work even with no script
    imageElement.style.display      = 'none';

    var imageLoader = new Image();
    imageLoader.src = el.href;
    imageLoader.onload = function() {
        loaderElement.parentElement.removeChild(loaderElement);
        imageElement.style.position     = 'absolute';
        imageElement.style.top          = '50%';
        imageElement.style.left         = '50%';
        // here using the imageLoaders size instead of the imageElement..
        imageElement.style.marginTop    = '-' + (parseInt(imageLoader.height) / 2) + 'px';
        imageElement.style.marginLeft   = '-' + (parseInt(imageLoader.width) / 2) + 'px';
        imageElement.style.display      = 'block';
    }

回答by Fatih Acet

It's because IE can't calculate width and height of display: noneimages. Use visibility: hiddeninstead.

这是因为 IE 无法计算display: none图像的宽度和高度。使用visibility: hidden来代替。

回答by Phenomenal

Try

尝试

 function onImageLoad(img, maxWidth, maxHeight) {
   var width = img.width; // Problem is in here
   var height = img.height // Problem is in here
   if (height==0  && img.complete){
       setTimeOut(function(){onImageLoad(img, maxWidth, maxHeight);},50);
   }

 }

回答by Run CMD

    var screenW = screen.width;
    var screenH = screen.height;
    //alert( screenW );
    function checkFotoWidth( img, maxw )
    {
        if( maxw==undefined)
            maxw = 200;
        var imgW = GetImageWidth(img.src);
        var imgH = GetImageHeight(img.src);
            //alert(GetImageWidth(img.src).toString()); // img.width); // objToString(img));
        if (imgW > maxw || (img.style.cursor == "hand" && imgW == maxw))
        {
            if (imgW > screenW) winW = screenW;
            else winW = imgW;

            if (imgH > screenH) winH = screenH;
            else winH = imgH;

            img.width=maxw;
            img.style.cursor = "pointer";

            img.WinW = winW;
            img.WinH = winH;
            //alert("winW : " + img.WinW);
            img.onclick = function() { openCenteredWindow("Dialogs/ZoomWin.aspx?img=" + this.src, this.WinW, this.WinH, '', 'resizable=1'); }
            img.alt = "Klik voor een uitvergroting :: click to enlarge :: klicken Sie um das Bild zu vergr?ssern";
            //alert("adding onclick);
        }
    }

    function GetImageWidth(imgSrc) 
    {
        var img = new Image();
        img.src = imgSrc;
        return img.width;
    } 

    function GetImageHeight(imgSrc) 
    {
        var img = new Image();
        img.src = imgSrc;
        return img.height;
    } 

回答by Pointy

I'd try this:

我会试试这个:

function onImageLoad(img, maxWidth, maxHeight) {
   var width, height;
   if ('currentStyle' in img) {
     width = img.currentStyle.width;
     height = img.currentStyle.height;
   }
   else {
     width = img.width;
     height = img.height;
   }
   // whatever
}

edit— and apparently if I were to try that I'd learn it doesn't work :-) OK, well "width" and "height" definitely seem to be attributes of <img>elements as far as IE is concerned. Maybe the problem is that the "load" event is firing for the element at the wrong time. To check whether that's the case, I would then try this:

编辑- 显然,如果我要尝试,我会发现它不起作用:-) 好吧,<img>就 IE 而言,“宽度”和“高度”似乎绝对是元素的属性。也许问题在于“加载”事件在错误的时间为元素触发。要检查是否是这种情况,我会尝试以下操作:

function onImageLoad(img, maxWidth, maxHeight) {
   var width, height;
   var i = new Image();
   i.onload = function() {
     width = i.width; height = i.height;
     // ... stuff you want to do ...
   };
   i.src = img.href;
}

回答by Moe

getDisplay().getImage().setUrl(imgURL);
final Image img = new Image(imgURL);
int w=img.getWidth();
int h=img.getHeight();