我正在根据我在此处找到的解决方案将图像加载到内存中,这很好,但由于它在回调中,因此属性宽度和高度在它之外是未定义的。
var originalWidth, originalHeight;
$("<img/>") // Make in memory copy of image to avoid css issues
.attr("src", $(img).attr("src"))
.load(function() {
originalWidth = this.width; // Note: $(this).width() will not
originalHeight = this.height; // work for in memory images.
});
console.log(originalWidth); // undefined obviously since `this` is only accessible within `load`s callback.
我想也许把它放在一个像这样的对象中:
var originalWidth, originalHeight;
var imgDimensions = {};
$("<img/>") // Make in memory copy of image to avoid css issues
.attr("src", $(img).attr("src"))
.load(function() {
imgDimensions.originalWidth = this.width; // Note: $(this).width() will not
imgDimensions.originalHeight = this.height; // work for in memory images.
});
console.log(imgDimensions['originalWidth']); // undefined also
如何从 load() 中返回这些属性?