Javascript 如何加载内容(包括内容和图像),然后加载fadein?
为什么加载了内容,但图像仍在加载? 如何加载内容(包括内容的图像)然后加载fadein jsJavascript 如何加载内容(包括内容和图像),然后加载fadein?,javascript,jquery,fadein,Javascript,Jquery,Fadein,为什么加载了内容,但图像仍在加载? 如何加载内容(包括内容的图像)然后加载fadein js $(document).ready(function(){ $('#contents').fadeOut('slow', function(){ $(this).load("url", {}, function(){ $("#contents").fadeIn('slow', function(){ alert('Fad
$(document).ready(function(){
$('#contents').fadeOut('slow', function(){
$(this).load("url", {}, function(){
$("#contents").fadeIn('slow', function(){
alert('Faded in!');
});
});
});
});
这并不是那么简单。您需要将加载处理程序加载到动态加载的图像上,但如果不修改源HTML,则在它们开始加载之前无法执行此操作,这会使加载过程变得更为复杂,因为有些处理程序可能会在您检查之前完成。因此,您可以这样做,获取动态加载内容中的所有图像对象,然后检查每个对象是否已完成加载。如果它还没有完成加载,那么将安装一个onload处理程序,以便我们可以计算最后一个处理程序何时完成加载。加载完成后,我们可以执行
fadeIn()
:
或者,为了解决这个问题,这里有一个通用的jQuery方法,它加载内容,然后在内容和内容中的所有图像都加载完毕后调用回调。这将更加可重用,并且可能使代码更具可读性。您使用它就像
.load(url、数据、fn)方法一样
:
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!');
});
});
});
});
太好了!!非常详细。我用了第二个。非常感谢!
$(document).ready(function(){
$('#contents').fadeOut('slow', function(){
$(this).loadComplete("url", {}, function(){
$("#contents").fadeIn('slow', function(){
alert('Faded in!');
});
});
});
});