使用 JavaScript 获取图像的实际宽度和高度?(在 Safari/Chrome 中) [英] Get the real width and height of an image with JavaScript? (in Safari/Chrome)

查看:35
本文介绍了使用 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.

您还可以使用 naturalHeightnaturalWidth HTML5 属性.

You can also use the naturalHeight and naturalWidth HTML5 attributes.

这篇关于使用 JavaScript 获取图像的实际宽度和高度?(在 Safari/Chrome 中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆