【问题标题】:Why doesn't this get an image's native dimensions?为什么这不能获得图像的原生尺寸?
【发布时间】:2014-02-07 23:51:09
【问题描述】:

我正在制作灯箱,我需要获取要显示的图像元素的原生尺寸。我正在研究一种基于 CSS-Tricks 的off this tutorial 方法。我的图片本身是 400x400 像素,但我的方法一直返回 0x0。以下是相关代码:

    function setLuxboxSize () {
    console.log("picture original: " + luxpic.attr('src'));

    var testingImage = new Image();

    testingImage.src = luxpic.attr('src');

    //console.log('testingImage src:' + testingImage.attr('src'));


    var picWidth = testingImage.width;
    var picHeight = testingImage.height;


    console.log("original width: " + picWidth);
    console.log("original height: " + picHeight);
};

此外,当注释掉的 console.log 行处于活动状态时,我在控制台中收到以下错误:Uncaught TypeError: Object # has no method 'attr'。第一个 console.log 行按预期返回一个 src。我做错了什么?

编辑:问题是图像尚未加载,并且宽度和高度调用在加载之前不会返回正确的值。查看 LorDex 或 Satpal 的答案以使用 onload 函数获取尺寸。

【问题讨论】:

  • luxpic 变量是什么?您的代码期望它是一个包装好的 jQuery 结果,例如 var luxpic = $("#image");
  • 哦,是的,这些东西是在别处定义的,不过我没有把那部分说出来:)

标签: jquery html image src


【解决方案1】:

您可以在加载后检查实际图像大小。为此,请使用 .onload() 方法:

testingImage.onLoad(function() {
    var picWidth = testingImage.width;
    var picHeight = testingImage.height;
    console.log("original width: " + picWidth);
    console.log("original height: " + picHeight);
});

【讨论】:

    【解决方案2】:

    您必须先加载图像,然后才能检查其尺寸。

    var testingImage = new Image();
    testingImage.src = luxpic.attr('src');
    testingImage.onload = function () { 
        var picWidth = this.width;
        var picHeight = this.height;
    
        console.log("original width: " + picWidth);
        console.log("original height: " + picHeight);
    };
    

    【讨论】:

      猜你喜欢
      • 2011-08-29
      • 2020-04-19
      • 2015-09-12
      • 1970-01-01
      • 2023-02-14
      • 1970-01-01
      • 1970-01-01
      • 2011-09-20
      • 2014-03-07
      相关资源
      最近更新 更多