【问题标题】:Get Each Image Natural Height With jQuery使用 jQuery 获取每个图像的自然高度
【发布时间】:2014-02-17 07:02:58
【问题描述】:

我必须读取每张图片的自然高度并进行计算。但是我在读取到自然高度时遇到了一些问题。

$('div.imgkirp img').each(function(){
    console.log($(this).naturalHeight);
});

它在控制台日志中得到:(图像编号)未定义。如何读取每个图像的自然高度?

【问题讨论】:

    标签: javascript jquery image


    【解决方案1】:

    尝试使用图片的属性naturalHeight,使用jQueryprop方法

    $('div.imgkirp img').each(function(){
    
       console.log($(this).prop('naturalHeight'));
    });
    

    【讨论】:

    • 也试过了,但对我不起作用。返回“未定义”。
    • @ArtlyticalMedia 你应该使用load。因为如果图片没有加载,可能会返回“undefined”。
    【解决方案2】:
    var image = new Image();
    image.src = $(this).attr("src");
    alert('width: ' + image.naturalWidth + ' and height: ' + image.naturalHeight);
    

    此方法在 IE 8 及以下版本中不起作用,因为它不支持 “naturalWidth”和“naturalHeight”属性。要实现相同的功能,请使用此代码

    var image = new Image();
    image.src = $(this).attr("src");
    image.onload = function() {
    console.log('height: ' + this.height);
    };
    

    【讨论】:

    • 这行不通。我在 Chrome 中尝试过,我可以看到来源是正确的;我将它设置为新图像的 src 属性和 naturalHeight/naturalWidth 'undefined'。
    猜你喜欢
    • 2012-04-04
    • 2010-11-19
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    • 2012-02-08
    相关资源
    最近更新 更多