gpt4 book ai didi

javascript - 如何加载内容(包括内容的图像)然后淡入淡出?

转载 作者:行者123 更新时间:2023-11-30 13:18:55 25 4
gpt4 key购买 nike

为什么内容已加载,但图像仍在加载?如何加载内容(包括内容的图像)然后淡入?

js

$(document).ready(function(){
$('#contents').fadeOut('slow', function(){
$(this).load("url", {}, function(){

$("#contents").fadeIn('slow', function(){

alert('Faded in!');

});

});

});
});

最佳答案

这不是那么简单。您需要将加载处理程序加载到动态加载的图像上,但是在不修改源 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) 方法一样使用它:

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!');
});
});
});
});

关于javascript - 如何加载内容(包括内容的图像)然后淡入淡出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10992489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com