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


当前回答

为了补充Xavi的答案,Paul Irish的github David Desandro的gitgub提供了一个名为imagesLoaded()的函数,它的工作原理相同,并解决了一些浏览器的缓存图像不触发.load()事件的问题(使用聪明的original_src -> data_uri -> original_src切换)。

它被广泛使用并定期更新,这有助于它成为解决问题的最健壮的解决方案。

其他回答

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

使用HTML5中的naturalHeight和naturalWidth属性。

例如:

var h = document.querySelector('img').naturalHeight;

工作在IE9+, Chrome, Firefox, Safari和Opera(统计)。

My situation is probably a little different. I am dynamically changing the src of an image via javascript and needed to ensure that the new image is sized proportionally to fit a fixed container (in a photo gallery). I initially just removed the width and height attributes of the image after it is loaded (via the image's load event) and reset these after calculating the preferred dimensions. However, that does not work in Safari and possibly IE (I have not tested it in IE thoroughly, but the image doesn't even show, so...).

Safari保留了前一张图片的尺寸所以尺寸总是在后面一张图片上。我认为这和缓存有关。因此,最简单的解决方案是克隆图像并将其添加到DOM中(重要的是将其添加到DOM中以获得with和height)。给图像一个可见值为hidden(不要使用display none,因为它不起作用)。获得尺寸后,删除克隆。

下面是我使用jQuery的代码:

// Hack for Safari and others
// clone the image and add it to the DOM
// to get the actual width and height
// of the newly loaded image

var cloned, 
    o_width, 
    o_height, 
    src = 'my_image.jpg', 
    img = [some existing image object];

$(img)
.load(function()
{
    $(this).removeAttr('height').removeAttr('width');
    cloned = $(this).clone().css({visibility:'hidden'});
    $('body').append(cloned);
    o_width = cloned.get(0).width; // I prefer to use native javascript for this
    o_height = cloned.get(0).height; // I prefer to use native javascript for this
    cloned.remove();
    $(this).attr({width:o_width, height:o_height});
})
.attr(src:src);

这个解决方案在任何情况下都有效。

我检查了Dio的答案,它对我来说很有用。

$('#image').fadeIn(10,function () {var tmpW = $(this).width(); var tmpH = $(this).height(); });

确保你调用了所有的函数。在fadeIn()的召回函数中处理图像大小。

谢谢你。

根本问题是WebKit浏览器(Safari和Chrome)并行加载JavaScript和CSS信息。因此,JavaScript可能在计算CSS的样式效果之前执行,返回错误的答案。在jQuery中,我发现解决方案是等到文档。readyState == 'complete',例如,

jQuery(document).ready(function(){
  if (jQuery.browser.safari && document.readyState != "complete"){
    //console.info('ready...');
    setTimeout( arguments.callee, 100 );
    return;
  } 
  ... (rest of function) 

至于宽度和高度……根据你正在做的事情,你可能需要offsetWidth和offsetHeight,其中包括边界和填充。