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


当前回答

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

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/

其他回答

正如Luke Smith所说,图像加载是一团糟。它在所有浏览器上都不可靠。这个事实给了我极大的痛苦。缓存的图像在某些浏览器中根本不会触发事件,所以那些说“图像加载比setTimeout更好”的人是错误的。

卢克·史密斯的解决方案在这里。

关于如何在jQuery 1.4中处理这些混乱的问题,有一个有趣的讨论。

我发现这是相当可靠的设置宽度为0,然后等待“完成”属性为真,宽度属性来大于零。您还应该注意错误。

根本问题是WebKit浏览器(Safari和Chrome)并行加载JavaScript和CSS信息。因此,JavaScript可能在计算CSS的样式效果之前执行,返回错误的答案。在jQuery中,我发现解决方案是等到文档。readyState == 'complete',例如,

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

至于宽度和高度……根据你正在做的事情,你可能需要offsetWidth和offsetHeight,其中包括边界和填充。

$("#myImg").one("load",function(){
  //do something, like getting image width/height
}).each(function(){
  if(this.complete) $(this).trigger("load");
});

来自克里斯的评论:http://api.jquery.com/load-event/

关于从WebKit缓存加载图像时onload事件不会触发的问题,在已接受的回答中有很多讨论。

在我的例子中,onload触发了缓存图像,但高度和宽度仍然为0。一个简单的setTimeout解决了我的问题:

$("img").one("load", function(){
    var img = this;
    setTimeout(function(){
        // do something based on img.width and/or img.height
    }, 0);
});

我不能说为什么onload事件即使从缓存加载图像时也会触发(改进了jQuery 1.4/1.5?) -但如果你仍然遇到这个问题,可能是我的答案和var src = img.src;img。SRC = "";img。SRC = SRC;技巧是有用的。

(请注意,就我的目的而言,我不关心图像属性或CSS样式中的预定义维度——但根据Xavi的回答,您可能想要删除这些维度。或者克隆图像。)

这是跨浏览器的

var img = new Image();
$(img).bind('load error', function(e)
{
    $.data(img, 'dimensions', { 'width': img.width, 'height': img.height });                    
});
img.src = imgs[i];              

通过使用得到尺寸

$(this).data('dimensions').width;
$(this).data('dimensions').height;

干杯!