Nếu bạn đang interjecting html đáng tin cậy với jQuery.append() hoặc jQuery.html() vào "element1" và giá trị css của element2 của bạn có thể là div hoặc span được thả sang trái để phù hợp với element3 bạn sẽ không thể lấy offsetWidth, clientWidth, naturalWidth (google crome) của element3 với một bộ kích hoạt sự kiện mới.
var element1 = $('div.container');
while(i<=length){
var element2 = $('<span/>').attr({'id':''+[i]+'','class':'container'});
var element3 = $('<img/>').attr('src':''+source[i]+'','class':'img');
$(element1)children().remove();
$(element2).appendTo(element1).append(element3);
var elms = $(element3);
var chwidth = elms[i].offsetWidth // returns 0;
++i;
};
những gì bạn có thể làm là trả lại độ rộng ngữ cảnh của các phần tử trước khi chúng được tải.
while(i<=length){
$(element1).children().remove();
$(elemen2).appendTo(element1).append(element3);
var elms = $(element3);
var newelms = elms[i].load();
var chwidth = newelms[i]['context'].width // returns element3's contextual width
if(chwidth != 0) // make sure only the proper width is returned
var width = chwidth;
++i;
};
Nếu điều này không làm việc sau đó thử:
while(i<=length){
$(element1).children().remove();
$(elemen2).appendTo(element1).append(element3);
var elms = $(element3);
var newelms = elms[i].load(function(){
//get the widths inside the load context
var width = this.width();
//pass the single width or el[i].width to next function
};
++i;
};
Nguồn
2012-11-02 19:36:24
[Giải pháp] (http://stackoverflow.com/questions/544993/official-way-to-ask-jquery-wait-for-all-images-to-load-before-executing-something) trên SO . – ybo