我正在创建一个jQuery插件。

我如何得到真实的图像宽度和高度与Javascript在Safari?

Firefox 3、IE7和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();

但在Safari和谷歌等Webkit浏览器中,Chrome的值为0。


当前回答

这适用于我(safari 3.2),从窗口内发射。onload事件:

$(window).load(function() {
  var pic = $('img');

  pic.removeAttr("width"); 
  pic.removeAttr("height");

  alert( pic.width() );
  alert( pic.height() );
});

其他回答

使用HTML5中的naturalHeight和naturalWidth属性。

例如:

var h = document.querySelector('img').naturalHeight;

工作在IE9+, Chrome, Firefox, Safari和Opera(统计)。

如前所述,如果图像在缓存中,Xavi回答将不起作用。这个问题响应webkit没有对缓存的图像触发加载事件,所以如果在img标签中没有显式设置宽度/高度attrs,唯一可靠的获取图像的方法是等待窗口。加载要触发的事件。

窗外。加载事件总是会触发,所以在没有任何技巧的情况下,访问img的宽度/高度是安全的。

$(window).load(function(){

   //these all work

   $('img#someId').css('width');
   $('img#someId').width();
   $('img#someId').get(0).style.width;
   $('img#someId').get(0).width; 

});

如果需要获取可能被缓存的动态加载图像的大小(以前加载过),可以使用Xavi方法加上查询字符串来触发缓存刷新。缺点是它将导致对服务器的另一个请求,请求已经缓存并且应该已经可用的img。愚蠢的Webkit。

var pic_real_width   = 0,
    img_src_no_cache = $('img#someId').attr('src') + '?cache=' + Date.now();

$('<img/>').attr('src', img_src_no_cache).load(function(){

   pic_real_width = this.width;

});

ps:如果你在img中有一个QueryString。SRC,您将不得不解析它并添加额外的参数来清除缓存。

Webkit浏览器在图像加载后设置高度和宽度属性。我建议使用图像的onload事件,而不是使用超时。这里有一个简单的例子:

var img = $("img")[0]; // Get my img elem
var pic_real_width, pic_real_height;
$("<img/>") // Make in memory copy of image to avoid css issues
    .attr("src", $(img).attr("src"))
    .load(function() {
        pic_real_width = this.width;   // Note: $(this).width() will not
        pic_real_height = this.height; // work for in memory images.
    });

为了避免CSS对图像尺寸的影响,上面的代码在内存中复制了图像。这是FDisk提出的一个非常聪明的解决方案。

你也可以使用naturalHeight和naturalWidth HTML5属性。

这适用于我(safari 3.2),从窗口内发射。onload事件:

$(window).load(function() {
  var pic = $('img');

  pic.removeAttr("width"); 
  pic.removeAttr("height");

  alert( pic.width() );
  alert( pic.height() );
});

我已经做了一些变通的实用函数,使用imagesLoaded jquery插件: 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}));
            },

你可以通过传递url,函数和它的上下文来使用它。函数在图像加载后执行,并返回创建的图像及其宽度和高度。

waitForImageSize("image.png", function(w,h){alert(w+","+h)},this)