这次给大家带来,的注意事项有哪些,下面就是实战案例,一起来看一下。
需要材料:
一张loading动画的gif图片
基本逻辑:
模态框遮罩 + loading.gif动图,
默认隐藏模态框
页面开始发送ajax请求数据时,显示模态框
请求完成,隐藏模态框
下面我们通过django新建一个web应用,来简单实践下
实践
1.新建一个django项目,创建应用app01, 配置好路由和static,略。将gif动图放到静态文件夹下,结构如下:
2.视图中定义一个函数,它返回页面test.html:
def test(request):
return render(request, 'test.html')
3.test.html页面如下:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
<!-- 导入css样式 -->
<link rel="stylesheet" href="/static/css/loading.css" rel="external nofollow" >
<!-- 导入jquery 和 js文件 -->
<script src="/static/plugins/jquery-3.2.1.js"></script>
<script src="/static/js/loading.js"></script>
</head>
<body>
<h1>你好啊,朋友!</h1>
<hr>
<p id="content">
<p>正在请求服务器数据....</p>
</p>
<!-- 模态框部分 -->
<p class="loading hide">
<p class="gif"></p>
</p>
</body>
</html>
4.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;
5.js文件如下:
$(function () {
//准备请求数据,显示模态框
$('p.loading').show();
$.ajax({
url: /ajax_handler.html/,
type: 'get',
data: {},
success: function (response) {
var content = response.content;
$('#content').html(content);
//请求完成,隐藏模态框
$('p.loading').hide();
},
error: function () {
$('#content').html('server error...');
//请求完成,隐藏模态框
$('p.loading').hide();
}
})
});
说明:
页面载入后,开始发送ajax请求,从服务端ajax_handler视图请求数据,这时显示模态框
请求完成后,不论成功与否,隐藏模态框
6.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)})
效果如下:
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
以上就是js+css完善网页加载时的用户体验的详细内容。