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

后端 未结 30 2354
傲寒
傲寒 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:47

    Stumbled upon this thread trying to find an answer for my own question. I was trying to get an image's width/height in a function AFTER the loader, and kept coming up with 0. I feel like this might be what you're looking for, though, as it works for me:

    tempObject.image = $('<img />').attr({ 'src':"images/prod-" + tempObject.id + ".png", load:preloader });
    xmlProjectInfo.push(tempObject);
    
    function preloader() {
        imagesLoaded++;
        if (imagesLoaded >= itemsToLoad) { //itemsToLoad gets set elsewhere in code
            DetachEvent(this, 'load', preloader); //function that removes event listener
            drawItems();
        }   
    }
    
    function drawItems() {
        for(var i = 1; i <= xmlProjectInfo.length; i++)
            alert(xmlProjectInfo[i - 1].image[0].width);
    }
    
    0 讨论(0)
  • 2020-11-22 01:48

    The root problem is that WebKit browsers (Safari and Chrome) load JavaScript and CSS information in parallel. Thus, JavaScript may execute before the styling effects of CSS have been computed, returning the wrong answer. In jQuery, I've found that the solution is to wait until document.readyState == 'complete', .e.g.,

    jQuery(document).ready(function(){
      if (jQuery.browser.safari && document.readyState != "complete"){
        //console.info('ready...');
        setTimeout( arguments.callee, 100 );
        return;
      } 
      ... (rest of function) 
    

    As far as width and height goes... depending on what you are doing you may want offsetWidth and offsetHeight, which include things like borders and padding.

    0 讨论(0)
  • 2020-11-22 01:48

    Jquery has two properties called naturalWidth and naturalHeight, you can use in this way.

    $('.my-img')[0].naturalWidth 
    $('.my-img')[0].naturalHeight
    

    Where my-img is a class name used to select my image.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 01:50

    There is now a jQuery plugin, event.special.load, to deal with cases where the load event on a cached image doesn't fire: http://github.com/peol/jquery.imgloaded/raw/master/ahpi.imgload.js

    0 讨论(0)
  • 2020-11-22 01:51

    What about image.naturalHeight and image.naturalWidth properties?

    Seems to work fine back quite a few versions in Chrome, Safari and Firefox, but not at all in IE8 or even IE9.

    0 讨论(0)
提交回复
热议问题