我正在创建一个 jQuery 插件。
如何在 Safari 中使用 Javascript 获取真实的图像宽度和高度?
以下适用于 Firefox 3、IE7 和 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。
最佳答案
Webkit 浏览器会在图片加载后设置 height 和 width 属性。我建议不要使用超时,而是使用图像的 onload 事件。这是一个简单的例子:
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 建议的一个非常聪明的解决方案.
您还可以使用 naturalHeight
和 naturalWidth
HTML5 属性。
关于javascript - 使用 JavaScript 获取图像的真实宽度和高度? (在 Safari/Chrome 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/318630/