Getting image width on image load fails on IE

后端 未结 8 1353
自闭症患者
自闭症患者 2020-12-31 09:32

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

8条回答
  •  别那么骄傲
    2020-12-31 10:33

    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 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:

    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;
    }
    

提交回复
热议问题