loading.js简单实现
1.用于网页中数据加载时等待。效果简洁明了,显得界面更清爽自然:
2.实现简单,方便使用,只需一张图片loading.gif和一个loading.js,无样式。
源码+Demo下载:https://files.cnblogs.com/zhougaojun/loading.js.zip
3.js代码:
1 /** 2 * html Loading... 3 * @return {} 4 * @auth goolser 5 * @date 2015-1-5 6 */ 7 var Loading = { 8 handler:null, //setInterval执行函数的句柄 9 text:'Loading...', //Loading默认显示的文字 10 //获取滚动条距离上边顶部的距离 11 getScrollTop:function(){ 12 var scrollTop=0; 13 if(document.documentElement&&document.documentElement.scrollTop){ 14 scrollTop=document.documentElement.scrollTop; 15 }else if(document.body){ 16 scrollTop=document.body.scrollTop; 17 } 18 return scrollTop; 19 }, 20 //获取内部内容的总高度, 21 getScrollHeight:function(){ 22 return Math.max(document.body.scrollHeight,document.documentElement.scrollHeight); 23 }, 24 //是获取可见内容的高度 25 getHeight: function(){ 26 if(window.innerHeight!= undefined){ 27 return window.innerHeight; 28 }else{ 29 var B= document.body, D= document.documentElement; 30 return Math.min(D.clientHeight, B.clientHeight) 31 } 32 }, 33 //显示阴影 34 showShadow:function(){ 35 var maskHeight = this.getScrollHeight()+"px"; 36 var shadowDiv = document.createElement("div"); 37 shadowDiv.innerHTML = ""; 38 shadowDiv.setAttribute('id','shadowDiv_MASK'); 39 shadowDiv.setAttribute('style','position:fixed; position: absolute; z-index: 999;left:0;top:0;display:block;width:100%;height:'+maskHeight+'; opacity:0.6;filter: alpha(opacity=60);-moz-opacity: 0.6; background:#000;'); 40 var body = document.getElementsByTagName("body")[0]; 41 body.appendChild(shadowDiv); 42 }, 43 //关闭阴影 44 hideShadow:function(){ 45 var body = document.getElementsByTagName("body")[0]; 46 var shadowDiv_MASK = document.getElementById('shadowDiv_MASK'); 47 if(body && shadowDiv_MASK){ 48 body.removeChild(shadowDiv_MASK); 49 } 50 }, 51 //显示Loading 52 show:function(txt){ 53 var top = this.getScrollTop()+(this.getHeight()/2)+"px"; 54 Loading.showShadow(); 55 var me = this; 56 if(txt){ 57 me.text = txt; 58 } 59 var loadingDiv = document.createElement("div"); 60 loadingDiv.innerHTML = me.text; 61 loadingDiv.setAttribute('id','loadingDiv'); 62 loadingDiv.setAttribute('style','padding:5px;top:'+top+';left:50%;margin:-9px 0 0 -75px;z-index: 9999;text-indent:20px; background: url("img/loading.gif") no-repeat #fff 5px 50%;border:1px solid #0099cc;color:#0099cc;font-size:12px;width:150px;line-height:17px; height:18px;position:absolute;'); 63 var body = document.getElementsByTagName("body")[0]; 64 body.appendChild(loadingDiv); 65 var flag = true; 66 handler=setInterval(function(){ 67 if(flag){ 68 loadingDiv.innerHTML = ""; 69 flag = false; 70 }else{ 71 loadingDiv.innerHTML = me.text; 72 flag = true; 73 } 74 },300); 75 return handler; 76 }, 77 //关闭Loading 78 hide:function(){ 79 clearInterval(handler); 80 var body = document.getElementsByTagName("body")[0]; 81 var loadingDiv = document.getElementById('loadingDiv'); 82 if(body && loadingDiv){ 83 body.removeChild(loadingDiv); 84 } 85 Loading.hideShadow(); 86 } 87 }