You could do this various different ways.
(您可以通过各种不同的方式进行操作。)
It could be a subtle as a small status on the page saying "Loading...", or as loud as an entire element graying out the page while the new data is loading. (在页面上显示为“正在加载...”的小状态可能是微妙的,或者在加载新数据时整个页面变灰会使整个页面变灰。)
The approach I'm taking below will show you how to accomplish both methods. (我在下面采用的方法将向您展示如何完成这两种方法。)
The Setup (设置)
Let's start by getting us a nice "loading" animation from http://ajaxload.info I'll be using
(让我们从我将要使用的http://ajaxload.info获得一个不错的“加载”动画开始)
Let's create an element that we can show/hide anytime we're making an ajax request:
(让我们创建一个我们可以在发出ajax请求时显示/隐藏的元素:)
<div class="modal"><!-- Place at bottom of page --></div>
The CSS (CSS)
Next let's give it some flair:
(接下来,让我们看看:)
/* Start by setting display:none to make this hidden.
Then we position it in relation to the viewport window
with position:fixed. Width, height, top and left speak
for themselves. Background we set to 80% white with
our animation centered, and no-repeating */
.modal {
display: none;
position: fixed;
z-index: 1000;
top: 0;
left: 0;
height: 100%;
width: 100%;
background: rgba( 255, 255, 255, .8 )
url('http://i.stack.imgur.com/FhHRx.gif')
50% 50%
no-repeat;
}
/* When the body has the loading class, we turn
the scrollbar off with overflow:hidden */
body.loading .modal {
overflow: hidden;
}
/* Anytime the body has the loading class, our
modal element will be visible */
body.loading .modal {
display: block;
}
And finally, the jQuery (最后,jQuery)
Alright, on to the jQuery.
(好了,到jQuery。)
This next part is actually really simple: (下一部分实际上非常简单:)
$body = $("body");
$(document).on({
ajaxStart: function() { $body.addClass("loading"); },
ajaxStop: function() { $body.removeClass("loading"); }
});
That's it!
(而已!)
We're attaching some events to the body element anytime the ajaxStart
or ajaxStop
events are fired. (每当ajaxStart
或ajaxStop
事件时,我们都会在body元素上附加一些事件。)
When an ajax event starts, we add the "loading" class to the body. (当ajax事件开始时,我们将“ loading”类添加到正文中。)
and when events are done, we remove the "loading" class from the body. (当事件完成后,我们从主体中删除“ loading”类。)
See it in action: http://jsfiddle.net/VpDUG/4952/
(实际运行中查看它: http : //jsfiddle.net/VpDUG/4952/)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…