使用chrome中的jquery获取图像高度

时间:2012-11-06 19:14:17

标签: jquery image google-chrome height

我有这个问题:我想在div中获得少量图片的高度,但我遇到Chrome问题。我的所有尝试都返回0或NaN ..这是我的代码:

HTML:

<div class="mid">
    <div class="cimglist">
        <a href="#"><img src="img1.jpg"></a>
        <a href="#"><img src="img2.jpg"></a>
        <a href="#"><img src="img3.jpg"></a>
        <a href="#"><img src="img4.jpg"></a>
        <a href="#"><img src="img5.jpg"></a>
    </div>
</div>

JQuery的:

var CardsTotalImages = 0;
var CardsCurrentImage = 0;
var CardsHeights = [];

$('.cimglist img').each(function() {
    /*
    CardsHeights[CardsCurrentImage] = $(this).height(); 
    CardsCurrentImage++;
    //this works great on IE and FF
    */
    var img = new Image();
    img.onload(function() {
        CardsHeights[CardsCurrentImage] = parseInt($(this).height());
        CardsCurrentImage++;
    });
    img.src = $(this).attr('src');
});

我搜索了每个帖子以找到解决方案,但我得到的唯一有用信息是,Chrome必须首先加载图片,然后达到高度。

提前谢谢。

4 个答案:

答案 0 :(得分:0)

img.onload使用中:

var h = $(this).get(0).height; // height
var w = $(this).get(0).width; // width

答案 1 :(得分:0)

我希望所有这些事情都在$(document).ready(function () { });

之内

如果是这样,Chrome就没有理由无法从图像中抓取$(this).height()。您不需要img.onload那样

另外,请注意不要在JS中使用Capital名称命名变量,除非它们是Classes / Instsantiable对象

答案 2 :(得分:0)

为什么不一直使用jQuery?

var CardsTotalImages = 0;
var CardsCurrentImage = 0;
var CardsHeights = [];

$('.cimglist').on('load', 'img', function() {
    CardsHeights[CardsCurrentImage] = $(this).height() || this.height; // added an alternative just in case. i've seen firefox do strange things during my time as a front-end developer.
    CardsCurrentImage++;
});

修改

此代码应在呈现img元素之前运行。

答案 3 :(得分:0)

我找到了一个解决方案,希望它有所帮助。 我已经在img标签中设置了图像的尺寸,它也适用于Chrome。 说:

<img width="464" height="287" src="myimg.jpg">