我正在创建一个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。


当前回答

最近我需要找到宽度和高度设置默认大小的.dialog表示图形。我使用的解决方案是:

 graph= $('<img/>', {"src":'mySRC', id:'graph-img'});
    graph.bind('load', function (){
        wid = graph.attr('width');
        hei = graph.attr('height');

        graph.dialog({ autoOpen: false, title: 'MyGraphTitle', height:hei, width:wid })
    })

对我来说,这适用于FF3, Opera 10, IE 8,7,6

附注:你可能会在一些像LightBox或ColorBox这样的插件中找到更多的解决方案

其他回答

您可以使用HTML图像元素的naturalWidth和naturalHeight属性。(这里有更多信息)。

你可以这样使用它:

//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;

这似乎适用于所有浏览器,除了IE版本8及以下。

下面是一个跨浏览器的解决方案,当您所选择的图像加载时触发一个事件:http://desandro.github.io/imagesloaded/您可以在imagesLoaded()函数中查找高度和宽度。

这对缓存的和动态加载的图像都有效。

function LoadImage(imgSrc, callback){
  var image = new Image();
  image.src = imgSrc;
  if (image.complete) {
    callback(image);
    image.onload=function(){};
  } else {
    image.onload = function() {
      callback(image);
      // clear onLoad, IE behaves erratically with animated gifs otherwise
      image.onload=function(){};
    }
    image.onerror = function() {
        alert("Could not load image.");
    }
  }
}

使用此脚本:

function AlertImageSize(image) {
  alert("Image size: " + image.width + "x" + image.height);
}
LoadImage("http://example.org/image.png", AlertImageSize);

演示:http://jsfiddle.net/9543z/2/

另一个建议是使用imagesLoaded插件。

$("img").imagesLoaded(function(){
alert( $(this).width() );
alert( $(this).height() );
});

如前所述,如果图像在缓存中,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,您将不得不解析它并添加额外的参数来清除缓存。