Javascript可以访问原生图像大小吗?

Nat*_*ong 22 javascript size jquery image

我正在编写一个jQuery函数,我想访问图像的原生大小,以及页面上为其指定的大小.我想为每个设置一个变量.

怎么做的?

Geo*_*lly 33

现代浏览器

当我在2009年写回这个答案时,浏览器的格局就大不相同了.现在任何合理的现代浏览器都支持Pim Jager的使用img.naturalWidth建议img.naturalHeight.看看他的回答.

传统答案与超级旧浏览器兼容

// find the element
var img = $('#imageid');

/* 
 * create an offscreen image that isn't scaled
 * but contains the same image.
 * Because it's cached it should be instantly here.
 */

var theImage = new Image();
theImage.src = img.attr("src");

// you should check here if the image has finished loading
// this can be done with theImage.complete

alert("Width: " + theImage.width);
alert("Height: " + theImage.height);
Run Code Online (Sandbox Code Playgroud)


Pim*_*ger 16

这应该工作:

var img = $('#imageid')[0]; //same as document.getElementById('imageid');
var width = img.naturalWidth;
var height = img.naturalHeight;
Run Code Online (Sandbox Code Playgroud)

naturalWidth和naturalHeight返回图像响应的大小,而不是显示大小.

根据Josh的评论,这不支持跨浏览器,这可能是正确的,我在FF3中进行了测试

  • 它现在完全是跨平台的 (2认同)