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


当前回答

$("#myImg").one("load",function(){
  //do something, like getting image width/height
}).each(function(){
  if(this.complete) $(this).trigger("load");
});

来自克里斯的评论:http://api.jquery.com/load-event/

其他回答

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

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

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

在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>

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

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

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

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

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

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

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