我有一个检测图像大小的函数,我希望它返回一个包含宽度和高度的对象。在下面的代码中,函数中的sz.width 和 sz.height保存了值,但是在它们返回值之后它是未定义的。我错过了什么?
function getImgSize(imgSrc) {
var newImg = new Image();
newImg.onload = function() {
var height = newImg.height;
var width = newImg.width;
function s() {}
sz = new s();
sz.width = width;
sz.height = height;
$('#infunc').text("in function, w = "+sz.width+", h = "+sz.height);
return sz;
}
newImg.src = imgSrc; // this must be done AFTER setting onload
}
var sz = getImgSize("http://lorempixel.com/output/fashion-q-c-1920-1920-4.jpg");
$('#outfunc').text("outside function, w = "+sz.width+", h = "+sz.height);
jsfiddle:http: //jsfiddle.net/forgetcolor/LbxA3/