我正在使用此处找到的 ajaxify-html5.js 脚本:https://github.com/browserstate/ajaxify
该脚本运行良好,除了当内容加载时(大约第 145 行: $content.html(contentHtml).ajaxify();
)您仍然可以看到图像加载。我想创建一个函数,它删除“加载”类(通过 CSS 过渡淡入和淡出内容),但只有在 ajax 内容不仅被获取,而且完全加载时,才能避免显示部分加载的图像。
我尝试在第 146 行插入以下内容,但它没有被执行。
$content.load(function(){
alert('asds');
$body.removeClass('loading');
});
有什么想法吗?
谢谢!
更新:基于卡里姆答案的最终工作代码:
$content.html(contentHtml).ajaxify(); /* you could fade in here if you'd like */
var $imgs = $content.find("img");
var loadCounter = 0;
var nImages = $imgs.length;
$imgs.load(function () {
loadCounter++;
if(nImages === loadCounter) {
$body.removeClass("loading");
}
// trigger load event if images have
// been cached by the browser
}).each(function () {
if(this.complete) {
$(this).trigger("load");
}
});
最佳答案
我不确定这将如何适合该插件,但我在这种情况下使用的通用解决方案(我已尽力调整它以适应您的情况)如下:
$content.one("load", function() {
var $imgs = $(this).find("img");
$imgs.hide();
var loadCounter = 0;
var nImages = $imgs.length;
$imgs.load(function () {
loadCounter++;
if(nImages === loadCounter) {
// all the images have loaded
// reveal them, remove the loading indicator
$body.removeClass("loading");
$imgs.show();
}
// trigger load event if images have
// been cached by the browser
}).each(function () {
if(this.complete) {
$(this).trigger("load");
}
});
});
关于ajax 完成后的 jQuery .load() 函数。 100% 加载之前不显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8874263/