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

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

    I checked out the answer of Dio and it works great for me.

    $('#image').fadeIn(10,function () {var tmpW = $(this).width(); var tmpH = $(this).height(); });

    Make sure that you call all your functions aso. that handle with the image size in the recaller function of fadeIn().

    Thanks for this.

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

    If the image is already used, you sholud:

    1. set image simensions to initial

      image.css('width', 'initial'); image.css('height', 'initial');

    2. get dimensions

      var originalWidth = $(this).width(); var originalHeight = $(this).height();

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

    You can use the naturalWidth and naturalHeight properties of the HTML image element. (Here's more info).

    You would use it like this:

    //you need a reference to the DOM element, not a jQuery object. It would be better if you can use document.getElementByTagsName or ID or any other native method
    var pic = $("img")[0];
    var pic_real_width = pic.naturalWidth;
    var pic_real_height = pic.naturalHeight;
    

    It seems like this works in all browsers except on IE from version 8 and below.

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

    Here's a cross browser solution that triggers an event when your selected images are loaded: http://desandro.github.io/imagesloaded/ you can look up the height and width within the imagesLoaded() function.

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

    For functions where you do not want to alter the original placement or image.

    $(this).clone().removeAttr("width").attr("width");
    $(this).clone().removeAttr("height").attr("height);
    
    0 讨论(0)
  • 2020-11-22 01:30

    this works for me (safari 3.2), by firing from within the window.onload event:

    $(window).load(function() {
      var pic = $('img');
    
      pic.removeAttr("width"); 
      pic.removeAttr("height");
    
      alert( pic.width() );
      alert( pic.height() );
    });
    
    0 讨论(0)
提交回复
热议问题