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


当前回答

关于从WebKit缓存加载图像时onload事件不会触发的问题,在已接受的回答中有很多讨论。

在我的例子中,onload触发了缓存图像,但高度和宽度仍然为0。一个简单的setTimeout解决了我的问题:

$("img").one("load", function(){
    var img = this;
    setTimeout(function(){
        // do something based on img.width and/or img.height
    }, 0);
});

我不能说为什么onload事件即使从缓存加载图像时也会触发(改进了jQuery 1.4/1.5?) -但如果你仍然遇到这个问题,可能是我的答案和var src = img.src;img。SRC = "";img。SRC = SRC;技巧是有用的。

(请注意,就我的目的而言,我不关心图像属性或CSS样式中的预定义维度——但根据Xavi的回答,您可能想要删除这些维度。或者克隆图像。)

其他回答

正如Luke Smith所说,图像加载是一团糟。它在所有浏览器上都不可靠。这个事实给了我极大的痛苦。缓存的图像在某些浏览器中根本不会触发事件,所以那些说“图像加载比setTimeout更好”的人是错误的。

卢克·史密斯的解决方案在这里。

关于如何在jQuery 1.4中处理这些混乱的问题,有一个有趣的讨论。

我发现这是相当可靠的设置宽度为0,然后等待“完成”属性为真,宽度属性来大于零。您还应该注意错误。

在github检查这个存储库!

使用Javascript检查宽度和高度的好例子

https://github.com/AzizAK/ImageRealSize

-编辑的要求从一些评论。

Javascript代码:

 function CheckImageSize(){
var image = document.getElementById("Image").files[0];
           createReader(image, function (w, h) {

                alert("Width is: " + w + " And Height is: "+h);
});            
}


  function  createReader(file, whenReady) {
        var reader = new FileReader;
        reader.onload = function (evt) {
            var image = new Image();
            image.onload = function (evt) {
                var width = this.width;
                var height = this.height;
                if (whenReady) whenReady(width, height);
            };
            image.src = evt.target.result;
        };
        reader.readAsDataURL(file);
    }

和HTML代码:

<html>
<head>
<title>Image Real Size</title>
<script src="ImageSize.js"></script>
</head>
<body>
<input type="file" id="Image"/>
<input type="button" value="Find the dimensions" onclick="CheckImageSize()"/>
</body>
<html>

这适用于我(safari 3.2),从窗口内发射。onload事件:

$(window).load(function() {
  var pic = $('img');

  pic.removeAttr("width"); 
  pic.removeAttr("height");

  alert( pic.width() );
  alert( pic.height() );
});

函数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() );
});