问题
Looking for a way to get the dimensions (width and height) of an external image.
I have used prop()
and attr()
, but they don't return any values. Just an error.
Example:
<a href="pathtotheimage">some link</a>
回答1:
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;
});
回答2:
Looks like none has provided a working vanilla js answer.
var img = document.createElement('img')
img.src = 'http://domain.com/img.png'
img.onload = function() {
console.log( this.width )
console.log( this.height )
}
Here is a jsfiddle: http://jsfiddle.net/Ralt/VMfVZ/
回答3:
This isn't technically jQuery but I would go down the route of:
var image = new Image(), width, height;
image.src = 'http://whereyourimage.is/heresmyimage.jpg';
width = image.width;
height = image.height;
You can then access those values using width
and height
, for example alert('My image is ' + width + ' pixels accross.');
来源:https://stackoverflow.com/questions/10338613/jquery-how-to-get-the-dimensions-of-a-external-image