我正在编写一个 jQuery 函数,我想在其中访问图像的 native 大小以及页面上为其指定的大小。我想为每个设置一个变量。
这是怎么做到的?
最佳答案
现代浏览器
当我在 2009 年写下这个答案时,浏览器环境已经大不相同。如今任何相当现代的浏览器都支持 Pim Jager's suggestion使用 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);
关于javascript - Javascript 可以访问 native 图像大小吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1093137/