当ajax加载数据时有时需要等待,于是写了以下方法,在加载过程中在页面中间有个提示图标,加载中调用方法为$.loading(1),加载完成调用方法为$.loading(0)隐藏该图标。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax加载等待</title>
<meta name="HandheldFriendly" content="True">
</head>
<body>
<div id="test">显示loading等待弹层</div><br>
<div id="test1">隐藏loading等待弹层</div><br><br><br><br>
说明:其中的137、32分别图片的高和宽,为方便图片在页面中心,所以进行了手动计算。其中imgw为定义图片的宽度,img_ml为图像尺寸定义宽度的一半,img_mt为图片等比缩放后高度的一半。
<script src="javascripts/jquery-2.2.2.min.js"></script>
<script>
(function ($) {
$.extend({
loading: function (opts) {
jsopt = opts || 0;
var winw = $(document).width();
var imgw=winw*0.15;
var img_ml=imgw/2;
var img_mt=img_ml*137/32;
var html = $("<div id='js-load' style='height:auto;width:auto;position:absolute;top:50%;left:50%;z-index:9999'><img src='https://www.dvy.com.cn/logo.png' style='width: "+imgw+"px;margin-left:-"+img_ml+"px;margin-top: -"+img_mt+"px;'></div>");
if (jsopt == 1) {
if ($("#js-load").is(":visible") == false) {
if ($("#js-load").length <= 0) {
$("body").prepend(html);
}
$("#js-load").show();
}
}
if (jsopt == 0 && $("#js-load").length > 0) {
$("#js-load").hide();
$("#js-load").remove();
}
}
});
})(jQuery);
(function ($) {
// 页面加载
$("#test").click(function () {
$.loading(1)
});
$("#test1").click(function () {
$.loading(0)
});
})(jQuery);
</script>
</body>
</html>
达维营-前端网