我想在我的网站上放置一个“请稍候,正在加载”的旋转圆圈动画。我应该如何使用 jQuery 完成此操作?
最佳答案
您可以通过多种不同的方式来完成此操作。它可能是一个微妙的页面上的小状态,说“正在加载...”,或者像整个元素在加载新数据时使页面变灰一样响亮。我在下面采用的方法将向您展示如何完成这两种方法。
设置
让我们从 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 事件开始时,我们将“loading”类添加到主体中。当事件完成时,我们从正文中删除“loading”类。
关于jquery - 如何使用 jQuery 创建 "Please Wait, Loading..."动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1964839/