通过其 src 获取图像的自然宽度



如果我有一个带有网址的图像,例如img/160x180.jpg如何在jquery/javascript中单独使用它才能获得它的宽度和高度。 我试过了

alert($('<img src="img/160x180.jpg"/>').naturalWidth)

在下面的示例中,它返回未定义。

http://jsfiddle.net/D7dx6/

更新:

alert($('<img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif"/>')[0].width);

编辑 — 这实际上没有意义;它需要在事件处理程序中:

$('<img/>', {
  'load': function() { alert(this.width); },
  'src': 'http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif'
});

应该注意的是,该代码在IE上可能存在问题,因为如果在建立"load"处理程序之前设置了"src"并且在缓存中找到图像,它有时会丢球。在这种情况下,您可以执行以下操作:

$('<img/>', { 'load': function() { alert(this.width); } }).prop('src', 'http://...');

没有"naturalWidth"属性。

虽然在这种情况下它几乎无关紧要的开销,但你可以在没有jQuery的情况下做到这一点,就像这样:

var img = new Image();
img.onload = function() {
  alert(img.width);
};
img.src = "http://placekitten.com/300/400";

现在需要注意的一件事是,如果您正在查看实际的页面元素(即页面上<img>标签),它们可能具有覆盖真实大小的"宽度"属性。再次获取图像通常会将其从缓存中拉出,尽管移动设备上的大图像存在一些潜在的痛苦。

编辑 - 格雷厄姆指出有一个"naturalWidth",但目前没有得到很好的支持。

naturalWidthnaturalHeight 尚没有得到很好的支持:请参阅 https://developer.mozilla.org/en/DOM/HTMLImageElement。

确定图像的原始尺寸(无论它当前是否存在于 DOM 中)的纯 JavaScript 方法是使用 Image 对象。

var img = new Image();
img.src = 'path/to/img.jpg';
// you'll probably want to use setTimeout to wait until the imh.complete is true
console.log(img.width);

最新更新