我按照我在這裏找到的解決方案將圖像加載到內存中,這很好,但由於它在回調中,因此屬性寬度和高度在其外部是未定義的。從回調中訪問屬性
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')不會等待它完成。它說「當圖像被加載時,運行這些代碼行......」但是,它不會像你期望的那樣阻塞你的其他代碼。無論如何,你不應該依賴'load' - http://api.jquery.com/load-event/ - 向下滾動到「使用圖片時加載事件的注意事項」 – Ian