在调整大小后获取实际图像大小

19

我有一个页面,其中填充了缩略图,并使用CSS调整大小为150x150,当我点击缩略图时,页面会变暗,并显示出真实大小的图像。

目前,我需要手动创建一个包含所有图像实际高度的数组。为了解决设计问题和减少我的画廊手动操作,我需要在调整大小后(CSS)获取图像的实际高度。

我尝试过:

var imageheight = document.getElementById(imageid).height;

并且:

var imageheight = $('#' + imageid).height();

但都返回用CSS指定的150px属性。我该如何解决?谢谢


可能是 http://stackoverflow.com/questions/7682772/get-image-size-after-resize-javascript 的重复问题。 - user1280616
2
所以你正在加载所有全尺寸图像,而不是制作适当的缩略图?糟糕... - Guffa
我正在加载完整尺寸的图像,并在单击缩略图时显示它。 - Novak
3个回答

29

你可以使用“自然”的关键字来帮助解决问题:

使用 JavaScript:

var imageheight = document.getElementById(imageid).naturalHeight;

或者使用jQuery

var imageheight = $('#' + imageid).naturalHeight;

2
对于IE9+和其他主要浏览器,这些属性都是有效的。这是一个很好的答案!有人可能为此编写了一个jQuery插件。如果没有,这可能是一个有趣的想法。 - Yanick Rochon

19

你可以创建一个单独的图像对象来实现这一点。

function getImageDimensions(path,callback){
    var img = new Image();
    img.onload = function(){
        callback({
            width : img.width,
            height : img.height
        });
    }
    img.src = path;
}

getImageDimensions('image_src',function(data){
    var img = data;

    //img.width
    //img.height

});
那样,您将使用相同的图像,但不是DOM上的那个,因为其尺寸已被修改。据我所知,缓存的图像将使用此方法进行回收利用。因此,无需担心额外的HTTP请求。

2

@Dinesh的回答建议使用naturalHeightnaturalWidth属性,这是非常好的建议,应该被接受。

我想在这里补充两点,可以节省人们很多时间,因为我看到很多关于这个问题的SO帖子,而我自己也花了相当长的时间来解决它。

  1. naturalHeight may return 0 or undefined if called before the image is loaded. Just setting src attribute may not mean that the image is loaded immediately. I have seen that it is best to fetch it in onload.

    $('selector')[0].onload = function() {
      alert(this.naturalHeight);
      alert(this.naturalWidth);
    }
    
  2. If not using this, just $('selector').naturalHeight may not work. You may need to access the associated DOM element i.e $('selector')[0].naturalHeight or $('selector').get(0).naturalHeight since we are using native Javascript's attribute naturalHeight. See this SO post for more details.


1
我花了好几个小时想弄清楚为什么 naturalWidth 返回 undefined,现在我知道原因了 (+1)。 - Jose Manuel Abarca Rodríguez

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接