jQuery: how to get the dimensions of a external image?

天涯浪子 提交于 2019-12-11 04:09:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!