我正在创建一个jQuery插件。

我如何得到真实的图像宽度和高度与Javascript在Safari?

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和谷歌等Webkit浏览器中,Chrome的值为0。


当前回答

$(document).ready(function(){
                            var image = $("#fix_img");
                            var w = image.width();
                            var h = image.height();
                            var mr = 274/200;
                            var ir = w/h
                            if(ir > mr){
                                image.height(200);
                                image.width(200*ir);
                            } else{
                                image.width(274);
                                image.height(274/ir);
                            }
                        }); 

//此代码帮助显示200*274维度的图像

其他回答

函数getOriginalWidthOfImg(img_element) { var t = new Image(); T.src = (img_element。getAttribute吗?img_element.getAttribute("src"): false) || 返回t.width; }

您不需要从图像或图像维度属性中删除样式。只需用javascript创建一个元素,并获得创建的对象宽度。

另一个建议是使用imagesLoaded插件。

$("img").imagesLoaded(function(){
alert( $(this).width() );
alert( $(this).height() );
});

那么形象呢?naturalHeight和image。naturalWidth属性呢?

在Chrome、Safari和Firefox的一些版本中似乎都运行得很好,但在IE8甚至IE9中就完全不行。

对于不希望更改原始位置或图像的函数。

$(this).clone().removeAttr("width").attr("width");
$(this).clone().removeAttr("height").attr("height);

Jquery有两个属性叫做naturalWidth和naturalHeight,你可以这样使用。

$('.my-img')[0].naturalWidth 
$('.my-img')[0].naturalHeight

其中my-img是一个类名,用于选择我的图像。