Get the real width and height of an image with JavaScript? (in Safari/Chrome)

后端 未结 30 2349
傲寒
傲寒 2020-11-22 01:16

I am creating a jQuery plugin.

How do I get the real image width and height with Javascript in Safari?

The following works with Firefox 3, IE7 and Opera 9:

30条回答
  •  无人共我
    2020-11-22 01:48

    My situation is probably a little different. I am dynamically changing the src of an image via javascript and needed to ensure that the new image is sized proportionally to fit a fixed container (in a photo gallery). I initially just removed the width and height attributes of the image after it is loaded (via the image's load event) and reset these after calculating the preferred dimensions. However, that does not work in Safari and possibly IE (I have not tested it in IE thoroughly, but the image doesn't even show, so...).

    Anyway, Safari keeps the dimensions of the previous image so the dimensions are always one image behind. I assume that this has something to do with cache. So the simplest solution is to just clone the image and add it to the DOM (it is important that it be added to the DOM the get the with and height). Give the image a visibility value of hidden (do not use display none because it will not work). After you get the dimensions remove the clone.

    Here is my code using jQuery:

    // Hack for Safari and others
    // clone the image and add it to the DOM
    // to get the actual width and height
    // of the newly loaded image
    
    var cloned, 
        o_width, 
        o_height, 
        src = 'my_image.jpg', 
        img = [some existing image object];
    
    $(img)
    .load(function()
    {
        $(this).removeAttr('height').removeAttr('width');
        cloned = $(this).clone().css({visibility:'hidden'});
        $('body').append(cloned);
        o_width = cloned.get(0).width; // I prefer to use native javascript for this
        o_height = cloned.get(0).height; // I prefer to use native javascript for this
        cloned.remove();
        $(this).attr({width:o_width, height:o_height});
    })
    .attr(src:src);
    

    This solution works in any case.

提交回复
热议问题