正在寻找一种获取外部图像的尺寸(宽度和高度)的方式。
我已经使用prop()
和attr()
,但它们不返回任何值。只是一个错误。jQuery:如何获取外部图像的尺寸?
例子:
<a href="pathtotheimage">some link</a>
正在寻找一种获取外部图像的尺寸(宽度和高度)的方式。
我已经使用prop()
和attr()
,但它们不返回任何值。只是一个错误。jQuery:如何获取外部图像的尺寸?
例子:
<a href="pathtotheimage">some link</a>
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;
});
如果图像从浏览器缓存中提取,'.load'事件不会触发。请参阅[此问题](http://stackoverflow.com/q/3877027/901048)了解解决方案。 – Blazemonger 2012-04-26 18:12:51
这不是技术上的jQuery但我会往下走的路线:使用width
和height
var image = new Image(), width, height;
image.src = 'http://whereyourimage.is/heresmyimage.jpg';
width = image.width;
height = image.height;
然后,您可以访问这些值,例如alert('My image is ' + width + ' pixels accross.');
看起来像没有提供了一个工作香草JS答案。
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/
你唯一的办法就是装载图像。 (如果你使用JavaScript) – 2012-04-26 17:45:26
啊有道理,不能得到尺寸,如果图像没有加载。谢谢 – user759235 2012-04-26 20:28:31