我根据我在此处找到的解决方案将图像加载到内存中,这很好,但由于它位于回调内,因此属性宽度和高度在其外部未定义。
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() 中返回这些属性?
最佳答案
console.log
在加载函数触发之前执行,因此 originalWidth
尚未更新。
关于javascript - 从回调中访问属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13203327/