使用 JavaScript 获取图像的实际宽度和高度?(在 Safari/Chrome 中)
我正在创建一个 jQuery 插件.
I am creating a jQuery plugin.
如何在 Safari 中使用 Javascript 获取真实图像的宽度和高度?
How do I get the real image width and height with Javascript in Safari?
以下适用于 Firefox 3、IE7 和 Opera 9:
The following works with Firefox 3, IE7 and Opera 9:
var pic = $("img")
// need to remove these in of case img-element has set width and height
pic.removeAttr("width");
pic.removeAttr("height");
var pic_real_width = pic.width();
var pic_real_height = pic.height();
但在 Safari 和 Google Chrome 等 Webkit 浏览器中,值为 0.
But in Webkit browsers like Safari and Google Chrome values are 0.
Webkit 浏览器在加载图像后设置高度和宽度属性.我建议使用图像的 onload 事件,而不是使用超时.这是一个简单的例子:
Webkit browsers set the height and width property after the image is loaded. Instead of using timeouts, I'd recommend using an image's onload event. Here's a quick example:
var img = $("img")[0]; // Get my img elem
var pic_real_width, pic_real_height;
$("<img/>") // Make in memory copy of image to avoid css issues
.attr("src", $(img).attr("src"))
.load(function() {
pic_real_width = this.width; // Note: $(this).width() will not
pic_real_height = this.height; // work for in memory images.
});
为了避免 CSS 可能对图像尺寸产生的任何影响,上面的代码在内存中创建了一个图像副本.这是 FDisk 建议的非常聪明的解决方案.
To avoid any of the effects CSS might have on the image's dimensions, the code above makes an in memory copy of the image. This is a very clever solution suggested by FDisk.
您还可以使用 naturalHeight
和 naturalWidth
HTML5 属性.
You can also use the naturalHeight
and naturalWidth
HTML5 attributes.