jQuery:如何获取外部图像的尺寸?

时间:2012-04-26 17:44:13

标签: javascript jquery image dimensions

寻找获取外部图像的尺寸(宽度和高度)的方法。
我使用了prop()attr(),但它们没有返回任何值。只是一个错误。

示例:

<a href="pathtotheimage">some link</a>

3 个答案:

答案 0 :(得分:9)

var imgSrc = "http://server.com/your/image/path/here.jpg"
var _width, _height;
$("<img/>").attr("src", imgSrc).load(function() {
    _width = this.width; 
    _height = this.height;
 });

答案 1 :(得分:1)

看起来没有人提供过有效的香草回答。

var img = document.createElement('img')
img.src = 'http://domain.com/img.png'
img.onload = function() {
    console.log( this.width )
    console.log( this.height )
}

这是一个jsfiddle:http://jsfiddle.net/Ralt/VMfVZ/

答案 2 :(得分:-1)

这不是技术上的jQuery,但我会沿着这条路走下去:

var image = new Image(), width, height;
image.src = 'http://whereyourimage.is/heresmyimage.jpg';
width = image.width;
height = image.height;

然后,您可以使用widthheight访问这些值,例如alert('My image is ' + width + ' pixels accross.');