我的情況是,我需要使用JavaScript來檢查圖像的大小,然後執行取決於其width.Here一段代碼是我的代碼觸發圖像的onload
var width, height;
var img = new Image();
img.src = "pool.jpg";
img.onload = function() {
width = this.width;
height = this.height;
console.log(width);
}
console.log(width);
if (width > 0) {
console.log('in condition check');
//Some code to be executed
}
//Some other code to be executed which cannot be put in the onload portion
問題是img.onload
部分只有在下面的代碼完成執行後纔有效。是否有任何方法可以觸發img.onload
函數並以同步方式執行代碼。
介意告訴我的方式:) – iJade
它使用xmlhttprequest,但更完整和一個可怕的做法,沒有人使用,因爲當你能夠使用它,你有足夠的經驗來學習異步的方式,不阻止界面。您需要了解如何處理異步編程。 –