我有一个Ajax页面,其中包含一些预先加载的大图像。我觉得需要显示带有加载消息的div,然后在加载所有图像时将其淡出。目前我使用此代码:
$(function () {
$(window).load(function () {
$('#images-loading').css({
visibility: 'hidden'
})
.fadeTo(200, function () {
});
});
});
HTML只是放在页面<div id="images-loading"></div>
中,虽然它不起作用,但我不完全理解为什么。通过不工作,我的意思是,它不会淡出。它只是遗留下来。我必须说脚本放在实际的ajax内容本身,但只在刷新页面时触发。我缺乏自己解决这个问题的经验,所以我很感激我可以尝试的任何建议或一些改变。
答案 0 :(得分:1)
如果您想在本地检查图片加载,可以遍历所有img
元素并检查他们的load
事件或使用waitForImages等插件(免责声明:由我撰写) )。
在成功回调中,只需执行...
$imagesLoading = $('#images-loading');
$imagesLoading.show();
$("#container").waitForImages(function() {
$imagesLoading.fadeOut(200);
});
答案 1 :(得分:0)
目前你正在做一些小事:
/// this first line basically says run my contents when the DOM is ready
$(function () {
/// this second line says run my contents when the window is fully loaded
/// but you are enabling this only after the DOM has loaded. Depending on
/// the browser these two events can fire in either order so you may find
/// situations where nothing would happen.
$(window).load(function () {
/// then you hide your image div
$('#images-loading').css({
visibility: 'hidden'
})
/// but then ask it to fade in
.fadeTo(200, function () {
});
});
});
编写上述内容的更好方法是:
/// once the page has fully loaded - i.e. everything including
/// images is ready - then hide our loading message. Set this
/// listener first as it could fire at any time.
$(window).load(function () {
$('#images-loading').stop().fadeOut(200);
});
/// as soon as the DOM is ready, show our loading message
/// the DOM event should fire before window load
$(function(){
/// if you are learning it is far better to name your functions
/// and then reference them where they are needed. It makes things
/// easier to read.
function whenFadeIsComplete(){
alert('fade in complete');
}
/// rather than hide with setting style directly, use jQuery's own hide
/// function. Better still, use a CSS class directly on your #images-loading
/// element that implements `display:none;` or `opacity:0;` - this will
/// render more quickly than JavaScript and mean you avoid your
/// loading div flickering into view before the fade in starts.
$('#images-loading').hide().fadeTo(200, whenFadeIsComplete);
})
如果您尝试以上操作,它可能会解决您的问题,只有在您强制刷新页面时才能使用它。但是,您可能会发现如果图像在浏览器中缓存,您将看不到加载消息(因为页面加载太快) ..强制浏览器刷新将清除缓存 (在大多数浏览器中)并且会让您的消息有时间再次显示。