我正在创建一个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。


当前回答

我使用不同的方法,简单地使Ajax调用服务器,以获得图像对象在使用时的图像大小。

//make json call to server to get image size
$.getJSON("http://server/getimagesize.php",
{"src":url},
SetImageWidth
);

//callback function
function SetImageWidth(data) {

    var wrap = $("div#image_gallery #image_wrap");

    //remove height
     wrap.find("img").removeAttr('height');
    //remove height
     wrap.find("img").removeAttr('width');

    //set image width
    if (data.width > 635) {
        wrap.find("img").width(635);
    }
    else {
         wrap.find("img").width(data.width);
    }
}

当然还有服务器端代码:

<?php

$image_width = 0;
$image_height = 0;

if (isset ($_REQUEST['src']) && is_file($_SERVER['DOCUMENT_ROOT'] . $_REQUEST['src'])) {

    $imageinfo = getimagesize($_SERVER['DOCUMENT_ROOT'].$_REQUEST['src']);
    if ($imageinfo) {
       $image_width=  $imageinfo[0];
       $image_height= $imageinfo[1];
    }
}

$arr = array ('width'=>$image_width,'height'=>$image_height);

echo json_encode($arr);

?>

其他回答

如果图像已经被使用,你应该:

设置图像尺寸为初始值 image.css(“宽度”,“初始”); image.css(“高度”,“初始”); 得到维度 var originalWidth = $(this).width(); var originalHeight = $(this).height();

下面是一个跨浏览器的解决方案,当您所选择的图像加载时触发一个事件:http://desandro.github.io/imagesloaded/您可以在imagesLoaded()函数中查找高度和宽度。

如前所述,如果图像在缓存中,Xavi回答将不起作用。这个问题响应webkit没有对缓存的图像触发加载事件,所以如果在img标签中没有显式设置宽度/高度attrs,唯一可靠的获取图像的方法是等待窗口。加载要触发的事件。

窗外。加载事件总是会触发,所以在没有任何技巧的情况下,访问img的宽度/高度是安全的。

$(window).load(function(){

   //these all work

   $('img#someId').css('width');
   $('img#someId').width();
   $('img#someId').get(0).style.width;
   $('img#someId').get(0).width; 

});

如果需要获取可能被缓存的动态加载图像的大小(以前加载过),可以使用Xavi方法加上查询字符串来触发缓存刷新。缺点是它将导致对服务器的另一个请求,请求已经缓存并且应该已经可用的img。愚蠢的Webkit。

var pic_real_width   = 0,
    img_src_no_cache = $('img#someId').attr('src') + '?cache=' + Date.now();

$('<img/>').attr('src', img_src_no_cache).load(function(){

   pic_real_width = this.width;

});

ps:如果你在img中有一个QueryString。SRC,您将不得不解析它并添加额外的参数来清除缓存。

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

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

现在有一个jQuery插件,event.special。Load,用于处理缓存映像上的Load事件未触发的情况:http://github.com/peol/jquery.imgloaded/raw/master/ahpi.imgload.js