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


当前回答

对于不希望更改原始位置或图像的函数。

$(this).clone().removeAttr("width").attr("width");
$(this).clone().removeAttr("height").attr("height);

其他回答

Jquery有两个属性叫做naturalWidth和naturalHeight,你可以这样使用。

$('.my-img')[0].naturalWidth 
$('.my-img')[0].naturalHeight

其中my-img是一个类名,用于选择我的图像。

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

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

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

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

函数getOriginalWidthOfImg(img_element) { var t = new Image(); T.src = (img_element。getAttribute吗?img_element.getAttribute("src"): false) || 返回t.width; }

您不需要从图像或图像维度属性中删除样式。只需用javascript创建一个元素,并获得创建的对象宽度。

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属性。

您可以通过编程方式获取图像,并使用Javascript检查尺寸,而完全不需要处理DOM。

var img = new Image();
img.onload = function() {
  console.log(this.width + 'x' + this.height);
}
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';