使用JavaScript获取图像的真实宽度和高度?(在Safari/Chrome中)

Fra*_*ter 275 javascript safari jquery webkit google-chrome

我正在创建一个jQuery插件.

如何在Safari中使用Javascript获得真实的图像宽度和高度?

以下适用于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();
Run Code Online (Sandbox Code Playgroud)

但在像Safari和Google Chrome这样的Webkit浏览器中,值为0.

Xav*_*avi 354

Webkit浏览器在加载图像后设置height和width属性.我建议使用图像的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.
    });
Run Code Online (Sandbox Code Playgroud)

为了避免CSS可能对图像的尺寸产生任何影响,上面的代码会在图像的内存中复制.这是FDisk建议的一个非常聪明的解决方案.

您还可以使用naturalHeightnaturalWidthHTML5属性.

  • 您可能遇到的问题是`load()`将异步执行,因此如果您想访问`width`和`height` - 它们可能尚未设置.而是在`load()`本身做"魔术"! (10认同)
  • 这很聪明,不知道你可以做$(img).load(); (5认同)
  • FDisk的解决方案非常聪明.不幸的是,他编写的解决方案只有在缓存图像或页面已经完成下载时才有效.如果图像未缓存或者在`window.onload`之前调用此代码,则可能返回高度/宽度0.无论如何,我已经将FDisk的想法整合到上面的解决方案中. (5认同)
  • 当我尝试console.log(pic_real_height)时,我每次都得到undefined.chrome,FF,IE9. (5认同)
  • 除了`width`和`height`之外,您还应该删除`min-width`,`min-height`,`max-width`和`max-height`,因为它们也会影响图像尺寸. (3认同)
  • 我正在测试Firefox 3和$(文档).ready()也不能正常工作. (2认同)
  • 我最近了解到`img.src = img.src`在Chrome 3.0中不起作用.也就是说,我相信我可能找到了解决办法:将图像源设置为空字符串然后再返回原始源.我会更新我的答案. (2认同)

san*_*rom 280

使用HTML5中naturalHeightnaturalWidth属性.

例如:

var h = document.querySelector('img').naturalHeight;
Run Code Online (Sandbox Code Playgroud)

适用于IE9 +,Chrome,Firefox,Safari和Opera(统计数据).

  • 除非图像已存在于缓存中,否则这似乎不适用于最新版本的FireFox(30.0). (5认同)
  • @DavidJohnstone使用它们的一个例子可能有所帮助.但我同意,绝对值得更高. (3认同)

FDi*_*isk 60


function getOriginalWidthOfImg(img_element) {
    var t = new Image();
    t.src = (img_element.getAttribute ? img_element.getAttribute("src") : false) || img_element.src;
    return t.width;
}

您无需从图像或图像尺寸属性中删除样式.只需使用javascript创建一个元素并获取创建的对象宽度.

  • 几个月后,使用jquery克隆图像(使用最新的Chrome)并获取它的属性,总是返回0x0到目前为止,这是唯一有效的解决方案(已经测试了此页面中的所有其他解决方案)返回之前,我设置t =也是null. (3认同)
  • 这是避免css问题的一种非常聪明的方法.不幸的是,上面所述的解决方案仅在图像被缓存或已经完成下载时才有效.如果图像未缓存或者在`window.onload`之前调用此代码,则可能返回宽度0. (3认同)

小智 16

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

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

就宽度和高度而言...取决于你正在做什么,你可能想要offsetWidth和offsetHeight,其中包括边框和填充等内容.

  • `$(window).load(function(){...});`帮助我的情况 (6认同)

JKS*_*JKS 16

在接受的答案中有很多关于onload如果从WebKit缓存加载图像时事件不会触发的问题的讨论.

在我的情况下,onload火灾缓存图像,但高度和宽度仍为0.一个简单的setTimeout解决了我的问题:

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

onload即使从缓存加载图像(jQuery 1.4/1.5的改进?),我也无法说出为什么事件会被触发 - 但是如果你仍然遇到这个问题,可能我的答案和var src = img.src; img.src = ""; img.src = src;技术的组合将会工作.

(请注意,就我的目的而言,我并不关心图像属性或CSS样式中的预定义尺寸 - 但您可能希望根据Xavi的答案删除它们.或者克隆图像.)


Owe*_*wen 11

这适用于我(safari 3.2),通过在window.onload事件中解雇:

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

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

  alert( pic.width() );
  alert( pic.height() );
});
Run Code Online (Sandbox Code Playgroud)


Yëc*_*ëco 8

您可以通过编程方式获取图像并使用Javascript检查尺寸,而无需使用DOM.

var img = new Image();
img.onload = function() {
  console.log(this.width + 'x' + this.height);
}
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';
Run Code Online (Sandbox Code Playgroud)

  • 这是最好的解决方案!即使图像未预先加载或缓存,它也能正常工作. (2认同)

And*_*zie 6

怎么样image.naturalHeightimage.naturalWidth属性?

似乎可以在Chrome,Safari和Firefox中使用很多版本,但在IE8甚至IE9中都没有.


Fox*_*Fox 5

我们如何在没有闪烁真实图像的情况下获得正确的尺寸:

(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();});
});
Run Code Online (Sandbox Code Playgroud)

它适用于<img class ="toreaddimensions"......


Sam*_*tos 5

jQuery具有两个属性naturalWidth和naturalHeight,您可以通过这种方式使用。

$('.my-img')[0].naturalWidth 
$('.my-img')[0].naturalHeight
Run Code Online (Sandbox Code Playgroud)

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

  • 这些不是jQuery方法。“ naturalWidth”(和高度)是图像元素对象上的属性。https://developer.mozilla.org/en/docs/Web/API/HTMLImageElement (2认同)