我想在我的网站上放置一个“请等待,加载”旋转圆动画。我应该如何使用jQuery来实现这一点?
发布于 2009-12-27 09:23:58
您可以通过各种不同的方式来完成此操作。这可能是页面上显示“正在加载...”的小状态,也可能是在加载新数据时整个页面变灰的整个元素的声音。下面我采用的方法将向您展示如何实现这两种方法。
设置
首先,让我们从我将使用的http://ajaxload.info中获得一个很好的“加载”动画
让我们创建一个可以在发出ajax请求时随时显示/隐藏的元素:
<div class="modal"><!-- Place at bottom of page --></div>
CSS
接下来,让我们给它添加一些技巧:
/* 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;
}
最后是jQuery
好了,来看看jQuery吧。下一部分实际上非常简单:
$body = $("body");
$(document).on({
ajaxStart: function() { $body.addClass("loading"); },
ajaxStop: function() { $body.removeClass("loading"); }
});
就这样!每当触发ajaxStart
或ajaxStop
事件时,我们都会将一些事件附加到body元素。当ajax事件启动时,我们将“加载”类添加到主体中。当事件完成时,我们从主体中删除“加载”类。
将其付诸实践:http://jsfiddle.net/VpDUG/4952/
发布于 2009-04-15 05:03:49
至于实际加载图像,check out this site提供了一堆选项。
就在请求开始时显示带有此图像的DIV而言,您有以下几种选择:
A)手动显示和隐藏图像:
$('#form').submit(function() {
$('#wait').show();
$.post('/whatever.php', function() {
$('#wait').hide();
});
return false;
});
B)使用ajaxStart和ajaxComplete
$('#wait').ajaxStart(function() {
$(this).show();
}).ajaxComplete(function() {
$(this).hide();
});
使用它,元素将显示/隐藏任何请求。可能是好的,也可能是坏的,取决于需要。
C)对特定的请求使用单独的回调:
$('#form').submit(function() {
$.ajax({
url: '/whatever.php',
beforeSend: function() { $('#wait').show(); },
complete: function() { $('#wait').hide(); }
});
return false;
});
发布于 2009-12-27 11:45:47
除了Jonathan和Samir的建议(顺便说一句,这两个答案都很棒!)外,jQuery还内置了一些事件,当发出ajax请求时,它会为您触发这些事件。
这是ajaxStart
事件
在AJAX请求启动时显示正在加载的消息(并且没有活动的请求)。
...and它的兄弟,ajaxStop
事件
附加一个函数,该函数将在所有AJAX请求结束时执行。这是一个Ajax事件。
它们共同构成了一种很好的方式,可以在页面上的任何地方发生ajax活动时显示进度消息。
HTML:
<div id="loading">
<p><img src="loading.gif" /> Please Wait</p>
</div>
脚本:
$(document).ajaxStart(function(){
$('#loading').show();
}).ajaxStop(function(){
$('#loading').hide();
});
https://stackoverflow.com/questions/1964839
复制相似问题