我正在创建一个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事件,而不是使用超时。这里有一个简单的例子:

var img = $("img")[0]; // Get my img elem
var pic_real_width, pic_real_height;
$("<img/>") // Make in memory copy of image to avoid css issues
    .attr("src", $(img).attr("src"))
    .load(function() {
        pic_real_width = this.width;   // Note: $(this).width() will not
        pic_real_height = this.height; // work for in memory images.
    });

为了避免CSS对图像尺寸的影响,上面的代码在内存中复制了图像。这是FDisk提出的一个非常聪明的解决方案。

你也可以使用naturalHeight和naturalWidth HTML5属性。

其他回答

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

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

我们如何在不眨眼的情况下获得正确的真实尺寸:

(function( $ ){
   $.fn.getDimensions=function(){
         alert("First example:This works only for HTML code without CSS width/height definition.");
         w=$(this, 'img')[0].width;
         h=$(this, 'img')[0].height;

         alert("This is a width/height on your monitor: " + $(this, 'img')[0].width+"/"+$(this, 'img')[0].height);

         //This is bad practice - it shows on your monitor
         $(this, 'img')[0].removeAttribute( "width" );
         $(this, 'img')[0].removeAttribute( "height" );
         alert("This is a bad effect of view after attributes removing, but we get right dimensions: "+  $(this, 'img')[0].width+"/"+$(this, 'img')[0].height);
         //I'am going to repare it
         $(this, 'img')[0].width=w;
         $(this, 'img')[0].height=h;
         //This is a good practice - it doesn't show on your monitor
         ku=$(this, 'img').clone(); //We will work with a clone
         ku.attr( "id","mnbv1lk87jhy0utrd" );//Markup clone for a final removing
         ku[0].removeAttribute( "width" );
         ku[0].removeAttribute( "height" );
         //Now we still get 0
         alert("There are still 0 before a clone appending to document: "+ $(ku)[0].width+"/"+$(ku)[0].height);
         //Hide a clone
         ku.css({"visibility" : "hidden",'position':'absolute','left':'-9999px'}); 
         //A clone appending
         $(document.body).append (ku[0]);
         alert("We get right dimensions: "+ $(ku)[0].width+"/"+$(ku)[0].height);
         //Remove a clone
         $("#mnbv1lk87jhy0utrd").remove();

         //But a next resolution is the best of all. It works in case of CSS definition of dimensions as well.
         alert("But if you want to read real dimensions for image with CSS class definition outside of img element, you can't do it with a clone of image. Clone method is working with CSS dimensions, a clone has dimensions as well as in CSS class. That's why you have to work with a new img element.");
         imgcopy=$('<img src="'+ $(this, 'img').attr('src') +'" />');//new object 
         imgcopy.attr( "id","mnbv1lk87jhy0aaa" );//Markup for a final removing
         imgcopy.css({"visibility" : "hidden",'position':'absolute','left':'-9999px'});//hide copy 
         $(document.body).append (imgcopy);//append to document 
         alert("We get right dimensions: "+ imgcopy.width()+"/"+imgcopy.height());
         $("#mnbv1lk87jhy0aaa").remove();


   }
})( jQuery );

$(document).ready(function(){

   $("img.toreaddimensions").click(function(){$(this).getDimensions();});
});

<img class="toreaddimensions"…

我已经做了一些变通的实用函数,使用imagesLoaded jquery插件: https://github.com/desandro/imagesloaded

            function waitForImageSize(src, func, ctx){
                if(!ctx)ctx = window;
                var img = new Image();
                img.src = src;
                $(img).imagesLoaded($.proxy(function(){
                    var w = this.img.innerWidth||this.img.naturalWidth;
                    var h = this.img.innerHeight||this.img.naturalHeight;
                    this.func.call(this.ctx, w, h, this.img);
                },{img: img, func: func, ctx: ctx}));
            },

你可以通过传递url,函数和它的上下文来使用它。函数在图像加载后执行,并返回创建的图像及其宽度和高度。

waitForImageSize("image.png", function(w,h){alert(w+","+h)},this)

关于从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的回答,您可能想要删除这些维度。或者克隆图像。)

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

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

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

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