基本逻辑:
-
模态框遮罩 + loading.gif动图,
-
默认隐藏模态框
-
页面开始发送Ajax请求数据时,显示模态框
-
请求完成,隐藏模态框
下面我们通过Django新建一个web应用,来简单实践下
-
新建一个Django项目,创建应用app01, 配置好路由和static,略。将gif动图放到静态文件夹下,结构如下:
-
视图中定义一个函数,它返回页面
test.html
:
def test(request):
return render(request, 'test.html')
-
test.html
页面如下:
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/static/css/loading.css">
<script src="/static/plugins/jquery-3.2.1.js"></script>
<script src="/static/js/loading.js"></script>
</head>
<h1>你好啊,朋友!</h1>
<div id="content">
<p>正在请求服务器数据....</p>
</div>
<div class="loading hide">
<div class="gif"></div>
</div>
</body>
</html>
-
CSS样式如下:
.loading {
position: fixed;
top: 0;
bottom: 0;
right: 0;
left: 0;
background-color: black;
opacity: 0.4;
z-index: 1000;
.loading .gif {
height: 32px;
width: 32px;
background: url('/static/img/loading.gif');
position: fixed;
left: 50%;
top: 50%;
margin-left: -16px;
margin-top: -16px;
z-index: 1001;
}
说明:
-
通过设置
position: fixed
,并令上下左右为0,实现模态框覆盖整个页面;
-
设置gif动态图为背景,居中,来显示加载效果;
-
通过设置z-index值,令gif图悬浮在模态框上面;
-
background-color: black;
是为了看着明显,具体使用时可以设为
white
;
-
JS文件如下:
$(function () {
$('div.loading').show();
$.ajax({
url: "/ajax_handler.html/",
type: 'GET',
data: {},
success: function (response) {
var content = response.content;
$('#content').html(content);
$('div.loading').hide();
error: function () {
$('#content').html('server error...');
$('div.loading').hide();
});
说明:
-
页面载入后,开始发送Ajax请求,从服务端
ajax_handler
视图请求数据,这时显示模态框
-
请求完成后,不论成功与否,隐藏模态框
-
ajax_handler
视图如下,它模拟网络延迟,并返回一些字符串:
from django.http import JsonResponse
from django.utils.safestring import mark_safe
def ajax_handler(request):
import time
time.sleep(3)
msg = ''' XXX '''
return JsonResponse({"content": mark_safe(msg)})
-
效果如下:
-
如果显示不了gif动图,可能是浏览器缓存问题。项目完整代码在这里:
https://github.com/Ayhan-Huang/Loading
需要材料:一张loading动画的gif图片基本逻辑:模态框遮罩 + loading.gif动图,默认隐藏模态框页面开始发送Ajax请求数据时,显示模态框请求完成,隐藏模态框下面我们通过Django新建一个web应用,来简单实践下实践新建一个Django项目,创建应用app01, 配置好路由和static,略。将gif动图放到静态文件夹下,结构如下:视图中定义一个函数,它返回页面tes
function setImage(img,$el,method){
if(method == "div"){
$el.
css
("background-image","url(" + img.src +")");
}else if(method == "img"){
$el.
css
({
"content": "url("+img.
https://www.jianshu.com/p/104bbb01b222
https://cn.vue
js
.org/v2/guide/transitions.html#%E5%8D%95%E5%85%83%E7%B4%A0-%E7%BB%84%E4%BB%B6%E7%9A%84%E8%BF%87%E6%B8%A1
转载自:https://www.jianshu.com/p/104...