Get the real width and height of an image with Jav

2018-12-31 03:39发布

I am creating a jQuery plugin.

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

Following works with Firefox 3, IE7 and Opera 9:

var pic = $("img")

// need to remove these in of case img-element has set width and height
pic.removeAttr("width"); 
pic.removeAttr("height");

var pic_real_width = pic.width();
var pic_real_height = pic.height();

But in Webkit browsers like Safari and Google Chrome values are 0.

30条回答
不流泪的眼
2楼-- · 2018-12-31 04:19

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() );
});
查看更多
公子世无双
3楼-- · 2018-12-31 04:20

I've done some workaround utility function, using imagesLoaded jquery plugin: https://github.com/desandro/imagesloaded

            function waitForImageSize(src, func, ctx){
                if(!ctx)ctx = window;
                var img = new Image();
                img.src = src;
                $(img).imagesLoaded($.proxy(function(){
                    var w = this.img.innerWidth||this.img.naturalWidth;
                    var h = this.img.innerHeight||this.img.naturalHeight;
                    this.func.call(this.ctx, w, h, this.img);
                },{img: img, func: func, ctx: ctx}));
            },

You can use this by passing url, function and its context. Function is performed after image is loaded and return created image, its width and height.

waitForImageSize("image.png", function(w,h){alert(w+","+h)},this)
查看更多
泪湿衣
4楼-- · 2018-12-31 04:20

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.

查看更多
美炸的是我
5楼-- · 2018-12-31 04:22

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.

查看更多
情到深处是孤独
6楼-- · 2018-12-31 04:23

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();

查看更多
余欢
7楼-- · 2018-12-31 04:25

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.

查看更多
登录 后发表回答