javascript - Javascript 可以访问 native 图像大小吗?

标签 javascript jquery image size

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

这是怎么做到的?

最佳答案

现代浏览器

当我在 2009 年写下这个答案时,浏览器环境已经大不相同。如今任何相当现代的浏览器都支持 Pim Jager's suggestion使用 img.naturalWidthimg.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);

关于javascript - Javascript 可以访问 native 图像大小吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1093137/

相关文章:

Javascript - 动态添加的选项卡在 Kendo 面板栏中不显示为选项卡

javascript - 来自 lambda 函数的 API 网关的 502 内部服务器错误响应

javascript - History.replaceState() 在控制台中给出 404 错误

javascript - 请任何人为Web中的表结构提供帮助

c# - 如何使用WPF/BitmapImage快速加载和显示图片?

python - 保存base64图像python

内部与外部构造函数的 JavaScript 类属性

javascript - 变量在 iPad 上未定义与在浏览器中定义的原因是什么?

ios - 如何设置背景图片,但不在 Swift iOS 中的状态栏后面

jquery - Rails - AJAX 模式对话框?