【发布时间】: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"); -
哦,是的,这些东西是在别处定义的,不过我没有把那部分说出来:)