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

查看:345
本文介绍了用JavaScript获取图片的真实宽度和高度? (在Safari / Chrome中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b 我如何在Safari中使用Javascript获得真实图像宽度和高度?



以下是Firefox 3,IE7和Opera 9的作品:

  var pic = $(img)

//需要删除这些内容img-element设置了宽度和高度
pic.removeAttr(width);
pic.removeAttr(height);

var pic_real_width = pic.width();
var pic_real_height = pic.height();

但是在Webkit浏览器中,例如Safari和Google Chrome浏览器的值都是0.

解决方案

Webkit浏览器在加载图像后设置高度和宽度属性。我建议使用图像的onload事件,而不是使用超时。这里有一个简单的例子:

  var img = $(img)[0]; //获取我的img elem 
var pic_real_width,pic_real_height;
$(< img />)//在内存中复制图片以避免css问题
.attr(src,$(img).attr(src))
.load(function(){
pic_real_width = this.width; //注意:$(this).width()不会
pic_real_height = this.height; //为记忆影像。
});

为了避免CSS可能对图像尺寸产生的任何影响,上面的代码使内存图像的副本。这是 FDisk 建议的一个非常聪明的解决方案。



您也可以使用 naturalHeight naturalWidth HTML5属性。


I am creating a jQuery plugin.

How do I get real image width and height with Javascript in Safari?

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();

But in Webkit browsers like Safari and Google Chrome values are 0.

解决方案

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.
    });

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.

You can also use the naturalHeight and naturalWidth HTML5 attributes.

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

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