事实并非如此简单。您需要将加载处理程序加载到动态加载的图像上,但不修改源代码HTML,直到它们已经开始加载才会这样做,这使得它更复杂一些,因为在检查之前可能会完成一些操作。所以,你可以做这样的事情,它获取动态加载的内容中的所有图像对象,然后检查每个图像对象是否已完成加载。如果它尚未完成加载,则会安装一个onload处理程序,以便在最后一次加载完成时进行计数。当所有人都加载完毕,我们就可以做fadeIn()
:
$(document).ready(function(){
$('#contents').fadeOut('slow', function(){
var self = $(this);
function fadeIn() {
$("#contents").fadeIn('slow', function(){
alert('Faded in!');
});
}
self.load("url", {}, function() {
var imgs = self.find("img");
var imgsRemaining = imgs.length;
imgs.each(function() {
// if the image isn't already loaded, then attach an onload handler
if (!img.complete || !this.height || !this.width) {
this.onload = this.onerror = this.onabort = function() {
// decrement imgsRemaining
--imgsRemaining;
// if no more images to finish loading, then start the fade
if (imgsRemaining == 0) {
fadeIn();
}
});
} else {
// this image already loaded
--imgsRemaining;
}
});
// if there were no images that weren't loaded yet
if (imgsRemaining == 0) {
fadeIn();
}
});
});
});
或者,解决问题的一点点更通用的方式,下面是加载内容的通用jQuery的方法,然后调用回调当内容和内容中的所有图像都完成加载时。这将更加可重用,并可能使您的代码更具可读性。您可以使用它就像.load(url, data, fn) method
:
jQuery.fn.loadComplete = function(url, data, fn) {
// check if optional data argument is missing
if (typeof data == "function") {
fn = data;
data = {};
}
// dynamically load the content
this.load(url, data, function() {
var self = this;
// when content is parsed, check to see when all images are loaded
var imgs = $(this).find("img");
var imgsRemaining = imgs.length;
imgs.each(function() {
if (this.complete) {
// if image is already loaded, just decrement the count
--imgsRemaining;
} else {
// image not loaded yet, install onload handler
this.onload = this.onerror = this.onabort = function() {
// when img has finished loading, check to see if all images are now loaded
if (--imgsRemaining == 0) {
fn.call(self);
}
};
}
});
if (imgsRemaining == 0) {
fn.call(self);
}
});
}
所以,用这种新方法,您的代码将仅仅是这样的:
$(document).ready(function(){
$('#contents').fadeOut('slow', function(){
$(this).loadComplete("url", {}, function(){
$("#contents").fadeIn('slow', function(){
alert('Faded in!');
});
});
});
});
那伟大的!非常详细。我用了第二个,非常感谢! – user964351