欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

【APICloud系列|27】 UICalendar模块(日历)的实现

程序员文章站 2022-03-19 15:30:56
导读:UICalendar 是一个日历选择模块;可自定义日历的样式,添加特殊日期标注,切换月份,设置指定日期;用于实现常用的日期选择,日历展示功能模块地址UICalendar 是一个日历选择模块;可自定义日历的样式,添加特殊日期标注,切换月份,设置指定日期;用于实现常用的日期选择,日历展示功能。UICalendar模块demo分享,项目里新建个页面,把demo的代码放到此页面上,添加上UICalendar模块,编译自定义loader查看效果。项目结构:config.xml&l.....

导读:UICalendar 是一个日历选择模块;可自定义日历的样式,添加特殊日期标注,切换月份,设置指定日期;用于实现常用的日期选择,日历展示功能

模块地址

UICalendar 是一个日历选择模块;可自定义日历的样式,添加特殊日期标注,切换月份,设置指定日期;用于实现常用的日期选择,日历展示功能。

UICalendar模块demo分享,项目里新建个页面,把demo的代码放到此页面上,添加上UICalendar模块,编译自定义loader查看效果。 

项目结构:

【APICloud系列|27】 UICalendar模块(日历)的实现

config.xml

<?xml version="1.0" encoding="UTF-8"?>

<widget id="A6075057351155" version="0.0.1"> 
  <name>日历</name>  
  <description>UICalendar 是一个日历选择模块;可自定义日历的样式,添加特殊日期标注,切换月份,设置指定日期;用于实现常用的日期选择,日历展示功能</description>  
  <author email="1978195254@qq.com" href="https://blog.csdn.net/weixin_41937552">Developer</author>  
  <content src="index.html"/>  
  <preference name="pageBounce" value="false"/>  
  <preference name="appBackground" value="rgba(0,0,0,0.0)"/>  
  <preference name="windowBackground" value="rgba(0,0,0,0.0)"/>  
  <preference name="frameBackgroundColor" value="rgba(0,0,0,0.0)"/>  
  <preference name="hScrollBarEnabled" value="false"/>  
  <preference name="vScrollBarEnabled" value="false"/>  
  <preference name="autoLaunch" value="true"/>  
  <preference name="fullScreen" value="false"/>  
  <preference name="autoUpdate" value="true"/>  
  <preference name="smartUpdate" value="false"/>  
  <preference name="debug" value="true"/>  
  <preference name="statusBarAppearance" value="true"/>  
  <permission name="readPhoneState"/>  
  <permission name="camera"/>  
  <permission name="record"/>  
  <permission name="location"/>  
  <permission name="fileSystem"/>  
  <permission name="internet"/>  
  <permission name="bootCompleted"/>  
  <permission name="hardware"/>  
  <access origin="*"/>  
  <preference name="querySchemes" value="alipay,alipayshare"/> 
</widget>

index.html

<!doctype html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,initial-scale=1.0,width=device-width" />
		<meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
		<title>日历</title>
		<link rel="stylesheet" type="text/css" href="./css/api.css" />
		<style type="text/css">
			html, body {
				height: 100%;
			}
			.wrap {
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-flex-flow: column;
			}
			header {
				height: 44px;
				width: 100%;
				text-align: center;
				background-color: #81a9c3;
				color: #fff;
				line-height: 44px;
				font-size: 20px;
			}
			.flex-1 {
				-webkit-box-flex: 1;
				-webkit-flex: 1;
			}
			footer {
				height: 30px;
				width: 100%;
				background-color: #81a9c3;
				color: white;
				line-height: 30px;
				text-align: center;
			}
		</style>
	</head>
	<body class="wrap">
		<header>
			APICloud
		</header>
		<section class="flex-1"></section>
		<footer>
			Copyright &copy;<span id="year"></span>
		</footer>
	</body>
	<script type="text/javascript" src="./script/api.js"></script>
	<script type="text/javascript">
		apiready = function() {
			//输出Log,Log将显示在APICloud Studio控制台
			console.log("Hello World! Hello APICloud!");
			var header = $api.dom('header');
			// 获取 header 标签元素
			var footer = $api.dom('footer');
			// 获取 footer 标签元素
			// 1.修复开启沉浸式效果带来的顶部Header与手机状态栏重合的问题,最新api.js方法已支持适配iPhoneX;
			// 2.默认已开启了沉浸式效果 config.xml中 <preference name="statusBarAppearance" value="true"/>
			// 3.沉浸式效果适配支持iOS7+,Android4.4+以上版本
			var headerH = $api.fixStatusBar(header);
			// 最新api.js为了适配iPhoneX增加的方法,修复底部Footer部分与iPhoneX的底部虚拟横条键重叠的问题;
			var footerH = $api.fixTabBar(footer);
			api.openFrame({
				name : 'uicalendar',
				url : 'html/uicalendar.html',
				bounces : true,
				rect : {// 推荐使用Margin布局,用于适配屏幕的动态变化
					marginTop : headerH, // main页面距离win顶部的高度
					marginBottom : footerH, // main页面距离win底部的高度
					w : 'auto' // main页面的宽度 自适应屏幕宽度
				}
			});
			// 获取当前年份时间,并加载显示到页面
			var year = $api.byId('year');
			year.innerHTML = new Date().getFullYear();
		};
	</script>
</html>

api.css

html{
	font-family: sans-serif;
}
html,body,header,section,footer,div,ul,ol,li,img,a,span,em,del,legend,center,strong,var,fieldset,form,label,dl,dt,dd,cite,input,hr,time,mark,code,figcaption,figure,textarea,h1,h2,h3,h4,h5,h6,p{
	margin:0;
	border:0;
	padding:0;
	font-style:normal;
}
html,body {
	-webkit-touch-callout:none;
	-webkit-text-size-adjust:none;
	-webkit-tap-highlight-color:rgba(0, 0, 0, 0);
	-webkit-user-select:none;
	background-color: #fff;
}
nav,article,aside,details,main,header,footer,section,fieldset,figcaption,figure{
	display: block;
}
img,a,button,em,del,strong,var,label,cite,small,time,mark,code,textarea{
	display:inline-block;
}
header,section,footer {
	position:relative;
}
ol,ul{
	list-style:none;
}
input,button,textarea {
	border:0;
	margin:0;
	padding:0;
	font-size:1em;
	line-height:1em;
	/*-webkit-appearance:none;*/
	background-color:rgba(0, 0, 0, 0);
}
span{
	display:inline-block;
}
a:active, a:hover {
  outline: 0;
}
a, a:visited{
	text-decoration:none;
}

label, .wordWrap{
    word-wrap: break-word;
    word-break: break-all;
}
table {
  border-collapse: collapse;
  border-spacing: 0;
}
td,th {
  padding: 0;
}
.clearfix:after{
	content: ' ';
	display: block;
	clear: both;
	visibility:hidden;
	line-height: 0;
	height:0;
}
.loading_more{
	display: block;
	height: 1.5em;
	width: 100%;
}
.loading_more:before {
	display: inline-block; vertical-align: text-bottom;
	content: ' '; height: 16px; width: 16px; margin-right: 6px;
	background: url(../image/loading_more.gif) no-repeat center;
	-webkit-background-size: contain;
	background-size: contain;
} 
.loading_more:after {
	content: '加载更多';	
}

uicalendar.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
		<meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
		<title>日历</title>
		<link rel="stylesheet" type="text/css" href="../css/api.css" />
		<style>
			html {
				background-color: white;
			}
			span {
				padding: 3px 3px;
				margin: 5px;
				display: inline-block;
				background-color: #e8e8e8;
			}
			.hover {
				opacity: .4;
			}
		</style>
	</head>
	<body style="padding-top: 340px;">
		<div class="main">
			<span tapmode="hover" onclick="fnSetSpecialDates()">setSpecialDates()</span>
			<span tapmode="hover" onclick="fnCancelSpecialDates()">cancelSpecialDates()</span>
			<span tapmode="hover" onclick="fnClose()">close()</span>
			<span tapmode="hover" onclick="fnShow()">show()</span>
			<span tapmode="hover" onclick="fnHide()">hide()</span>
			<span tapmode="hover" onclick="fnNextMonth()">nextMonth()</span>
			<span tapmode="hover" onclick="fnPrevMonth()">prevMonth()</span>
			<span tapmode="hover" onclick="fnNextYear()">nextYear()</span>
			<span tapmode="hover" onclick="fnPrevYear()">prevYear()</span>
			<span tapmode="hover" onclick="fnSetDate()">setDate()</span>
			<span tapmode="hover" onclick="fnTurnPage()">turnPage()</span>
		</div>
	</body>
	<script type="text/javascript" src="../script/api.js"></script>
	<script type="text/javascript">
		var UICalendar;
		apiready = function() {
			UICalendar = api.require('UICalendar');
			fnOpen();
		};
		function fnOpen() {
			UICalendar.open({
				rect : {
					x : 0,
					y : 0,
					w : api.frameWidth,
					h : 280
				},
				styles : {
					bg : '#81a9c3',
					week : {
						weekdayColor : '#3b3b3b',
						weekendColor : '#a8d400',
						size : 12
					},
					date : {
						color : '#3b3b3b',
						selectedColor : '#fff',
						selectedBg : '#a8d500',
						size : 12
					},
					today : {
						color : 'rgb(230,46,37)',
						bg : ''
					},
					specialDate : {
						color : '#fff'
					}
				},
				specialDate : [{
					date : '2018-10-10'
				}],
				switchMode : 'vertical',
				fixed : true,
				fixedOn : api.frameName
			}, function(ret, err) {
				if (ret) {
				} else {
					alert(JSON.stringify(err));
				}
			});
		}

		function fnSetSpecialDates() {
			UICalendar.setSpecialDates({
				specialDates : [{
					date : '2018-10-12',
					color : '#f0f',
					bg : '#0f0'
				}, {
					date : '2018-10-16',
					color : '#f0f',
					bg : '#0f0'
				}]
			});
		}

		function fnCancelSpecialDates() {
			UICalendar.cancelSpecialDates({
				specialDates : ['2018-10-12', '2018-10-16']
			});
		}

		function fnClose() {
			UICalendar.close();
		}

		function fnShow() {
			UICalendar.show();
		}

		function fnHide() {
			UICalendar.hide();
		}

		function fnNextMonth() {
			UICalendar.nextMonth(function(ret, err) {
				if (ret) {
					alert(JSON.stringify(ret));
				} else {
					alert(JSON.stringify(err));
				}
			});
		}

		function fnPrevMonth() {
			UICalendar.prevMonth(function(ret, err) {
				if (ret) {
					alert(JSON.stringify(ret));
				} else {
					alert(JSON.stringify(err));
				}
			});
		}

		function fnNextYear() {
			UICalendar.nextYear(function(ret, err) {
				if (ret) {
					alert(JSON.stringify(ret));
				} else {
					alert(JSON.stringify(err));
				}
			});
		}

		function fnPrevYear() {
			UICalendar.prevYear(function(ret, err) {
				if (ret) {
					alert(JSON.stringify(ret));
				} else {
					alert(JSON.stringify(err));
				}
			});
		}

		function fnSetDate() {
			UICalendar.setDate({
				date : '2018-10-18',
				ignoreSelected : false
			}, function(ret, err) {
				if (ret.status) {
					alert(JSON.stringify(ret));
				} else {
					alert(JSON.stringify(err));
				}
			});
		}

		function fnTurnPage() {
			UICalendar.turnPage({
				date : '2018-09-18'
			});
		}
	</script>
</html>

city.json

{
"list":{
  "first": [
      {
        "name": "山东省",
        "id": "1",
        "second": [{
            "name": "济南市",
            "id": "1",
                    "third": [
                      {
                        "name": "历下区",
                        "id": "1"
                      },
                      {
                        "name": "章丘市",
                        "id": "10"
                      },
                       {
                        "name": "高新区",
                        "id": "145"
                       },
                       {
                        "name": "市中区",
                        "id": "2"
                       },
                       {
                        "name": "槐荫区",
                        "id": "3"
                       },
                       {
                        "name": "天桥区",
                        "id": "4"
                       },
                       {
                        "name": "历城区",
                        "id": "5"
                       },
                       {
                        "name": "长清区",
                         "id": "6"
                       },
                       {
                        "name": "平阴县",
                        "id": "7"
                       },
                       {
                        "name": "济阳县",
                        "id": "8"
                       },
                       {
                        "name": "商河县",
                        "id": "9"
                       }
                      ]

                  }]
         },                  
        {
            "name":"黑龙江省",
            "id":"11",
            "second": [{
                "name": "哈尔滨市",
                "id": "145",
                        "third": [
                          {
                            "name": "道里区",
                            "id": "464"
                          },
                          {
                            "name": "道外区",
                            "id": "465"
                          },
                          {
                            "name": "南岗区",
                            "id": "466"
                              },
                              {
                                "name": "平房区",
                                "id": "467"
                              },
                              {
                                "name": "香坊区",
                                "id": "468"
                              },
                              {
                                "name": "松北区",
                                "id": "469"
                              },
                              {
                                "name": "动力区",
                                "id": "470"
                              },
                              {
                                "name": "开发区",
                                "id": "471"
                              },
                              {
                                "name": "依兰县",
                                "id": "472"
                              },
                              {
                                "name": "呼兰区",
                                "id": "473"
                              },
                              {
                                "name": "方正县",
                                "id": "474"
                              },
                              {
                                "name": "宾县",
                                "id": "475"
                              },
                              {
                                "name": "延寿县",
                                "id": "476"
                              },
                              {
                                "name": "巴彦县",
                                "id": "477"
                              },
                              {
                                "name": "阿城区",
                                "id": "478"
                              },
                              {
                                "name": "木兰县",
                                "id": "479"
                              },
                              {
                                "name": "双城市",
                                "id": "480"
                              },
                              {
                                "name": "通河县",
                                "id": "481"
                              },
                              {
                                "name": "尚志市",
                                "id": "482"
                              },
                              {
                                "name": "五常市",
                                "id": "483"
                              }

                  ]}
             ]}
          ]}
}

api.js

/*
 * 
 * Copyright (c) 2021 https://blog.csdn.net/weixin_41937552
 */
(function(window){
    var u = {};
    var isAndroid = (/android/gi).test(navigator.appVersion);
    var uzStorage = function(){
        var ls = window.localStorage;
        if(isAndroid){
           ls = os.localStorage();
        }
        return ls;
    };
    function parseArguments(url, data, fnSuc, dataType) {
        if (typeof(data) == 'function') {
            dataType = fnSuc;
            fnSuc = data;
            data = undefined;
        }
        if (typeof(fnSuc) != 'function') {
            dataType = fnSuc;
            fnSuc = undefined;
        }
        return {
            url: url,
            data: data,
            fnSuc: fnSuc,
            dataType: dataType
        };
    }
    u.trim = function(str){
        if(String.prototype.trim){
            return str == null ? "" : String.prototype.trim.call(str);
        }else{
            return str.replace(/(^\s*)|(\s*$)/g, "");
        }
    };
    u.trimAll = function(str){
        return str.replace(/\s*/g,'');
    };
    u.isElement = function(obj){
        return !!(obj && obj.nodeType == 1);
    };
    u.isArray = function(obj){
        if(Array.isArray){
            return Array.isArray(obj);
        }else{
            return obj instanceof Array;
        }
    };
    u.isEmptyObject = function(obj){
        if(JSON.stringify(obj) === '{}'){
            return true;
        }
        return false;
    };
    u.addEvt = function(el, name, fn, useCapture){
        if(!u.isElement(el)){
            console.warn('$api.addEvt Function need el param, el param must be DOM Element');
            return;
        }
        useCapture = useCapture || false;
        if(el.addEventListener) {
            el.addEventListener(name, fn, useCapture);
        }
    };
    u.rmEvt = function(el, name, fn, useCapture){
        if(!u.isElement(el)){
            console.warn('$api.rmEvt Function need el param, el param must be DOM Element');
            return;
        }
        useCapture = useCapture || false;
        if (el.removeEventListener) {
            el.removeEventListener(name, fn, useCapture);
        }
    };
    u.one = function(el, name, fn, useCapture){
        if(!u.isElement(el)){
            console.warn('$api.one Function need el param, el param must be DOM Element');
            return;
        }
        useCapture = useCapture || false;
        var that = this;
        var cb = function(){
            fn && fn();
            that.rmEvt(el, name, cb, useCapture);
        };
        that.addEvt(el, name, cb, useCapture);
    };
    u.dom = function(el, selector){
        if(arguments.length === 1 && typeof arguments[0] == 'string'){
            if(document.querySelector){
                return document.querySelector(arguments[0]);
            }
        }else if(arguments.length === 2){
            if(el.querySelector){
                return el.querySelector(selector);
            }
        }
    };
    u.domAll = function(el, selector){
        if(arguments.length === 1 && typeof arguments[0] == 'string'){
            if(document.querySelectorAll){
                return document.querySelectorAll(arguments[0]);
            }
        }else if(arguments.length === 2){
            if(el.querySelectorAll){
                return el.querySelectorAll(selector);
            }
        }
    };
    u.byId = function(id){
        return document.getElementById(id);
    };
    u.first = function(el, selector){
        if(arguments.length === 1){
            if(!u.isElement(el)){
                console.warn('$api.first Function need el param, el param must be DOM Element');
                return;
            }
            return el.children[0];
        }
        if(arguments.length === 2){
            return this.dom(el, selector+':first-child');
        }
    };
    u.last = function(el, selector){
        if(arguments.length === 1){
            if(!u.isElement(el)){
                console.warn('$api.last Function need el param, el param must be DOM Element');
                return;
            }
            var children = el.children;
            return children[children.length - 1];
        }
        if(arguments.length === 2){
            return this.dom(el, selector+':last-child');
        }
    };
    u.eq = function(el, index){
        return this.dom(el, ':nth-child('+ index +')');
    };
    u.not = function(el, selector){
        return this.domAll(el, ':not('+ selector +')');
    };
    u.prev = function(el){
        if(!u.isElement(el)){
            console.warn('$api.prev Function need el param, el param must be DOM Element');
            return;
        }
        var node = el.previousSibling;
        if(node.nodeType && node.nodeType === 3){
            node = node.previousSibling;
            return node;
        }
    };
    u.next = function(el){
        if(!u.isElement(el)){
            console.warn('$api.next Function need el param, el param must be DOM Element');
            return;
        }
        var node = el.nextSibling;
        if(node.nodeType && node.nodeType === 3){
            node = node.nextSibling;
            return node;
        }
    };
    u.closest = function(el, selector){
        if(!u.isElement(el)){
            console.warn('$api.closest Function need el param, el param must be DOM Element');
            return;
        }
        var doms, targetDom;
        var isSame = function(doms, el){
            var i = 0, len = doms.length;
            for(i; i<len; i++){
                if(doms[i].isSameNode(el)){
                    return doms[i];
                }
            }
            return false;
        };
        var traversal = function(el, selector){
            doms = u.domAll(el.parentNode, selector);
            targetDom = isSame(doms, el);
            while(!targetDom){
                el = el.parentNode;
                if(el != null && el.nodeType == el.DOCUMENT_NODE){
                    return false;
                }
                traversal(el, selector);
            }

            return targetDom;
        };

        return traversal(el, selector);
    };
    u.contains = function(parent,el){
        var mark = false;
        if(el === parent){
            mark = true;
            return mark;
        }else{
            do{
                el = el.parentNode;
                if(el === parent){
                    mark = true;
                    return mark;
                }
            }while(el === document.body || el === document.documentElement);

            return mark;
        }
        
    };
    u.remove = function(el){
        if(el && el.parentNode){
            el.parentNode.removeChild(el);
        }
    };
    u.attr = function(el, name, value){
        if(!u.isElement(el)){
            console.warn('$api.attr Function need el param, el param must be DOM Element');
            return;
        }
        if(arguments.length == 2){
            return el.getAttribute(name);
        }else if(arguments.length == 3){
            el.setAttribute(name, value);
            return el;
        }
    };
    u.removeAttr = function(el, name){
        if(!u.isElement(el)){
            console.warn('$api.removeAttr Function need el param, el param must be DOM Element');
            return;
        }
        if(arguments.length === 2){
            el.removeAttribute(name);
        }
    };
    u.hasCls = function(el, cls){
        if(!u.isElement(el)){
            console.warn('$api.hasCls Function need el param, el param must be DOM Element');
            return;
        }
        if(el.className.indexOf(cls) > -1){
            return true;
        }else{
            return false;
        }
    };
    u.addCls = function(el, cls){
        if(!u.isElement(el)){
            console.warn('$api.addCls Function need el param, el param must be DOM Element');
            return;
        }
        if('classList' in el){
            el.classList.add(cls);
        }else{
            var preCls = el.className;
            var newCls = preCls +' '+ cls;
            el.className = newCls;
        }
        return el;
    };
    u.removeCls = function(el, cls){
        if(!u.isElement(el)){
            console.warn('$api.removeCls Function need el param, el param must be DOM Element');
            return;
        }
        if('classList' in el){
            el.classList.remove(cls);
        }else{
            var preCls = el.className;
            var newCls = preCls.replace(cls, '');
            el.className = newCls;
        }
        return el;
    };
    u.toggleCls = function(el, cls){
        if(!u.isElement(el)){
            console.warn('$api.toggleCls Function need el param, el param must be DOM Element');
            return;
        }
       if('classList' in el){
            el.classList.toggle(cls);
        }else{
            if(u.hasCls(el, cls)){
                u.removeCls(el, cls);
            }else{
                u.addCls(el, cls);
            }
        }
        return el;
    };
    u.val = function(el, val){
        if(!u.isElement(el)){
            console.warn('$api.val Function need el param, el param must be DOM Element');
            return;
        }
        if(arguments.length === 1){
            switch(el.tagName){
                case 'SELECT':
                    var value = el.options[el.selectedIndex].value;
                    return value;
                    break;
                case 'INPUT':
                    return el.value;
                    break;
                case 'TEXTAREA':
                    return el.value;
                    break;
            }
        }
        if(arguments.length === 2){
            switch(el.tagName){
                case 'SELECT':
                    el.options[el.selectedIndex].value = val;
                    return el;
                    break;
                case 'INPUT':
                    el.value = val;
                    return el;
                    break;
                case 'TEXTAREA':
                    el.value = val;
                    return el;
                    break;
            }
        }
        
    };
    u.prepend = function(el, html){
        if(!u.isElement(el)){
            console.warn('$api.prepend Function need el param, el param must be DOM Element');
            return;
        }
        el.insertAdjacentHTML('afterbegin', html);
        return el;
    };
    u.append = function(el, html){
        if(!u.isElement(el)){
            console.warn('$api.append Function need el param, el param must be DOM Element');
            return;
        }
        el.insertAdjacentHTML('beforeend', html);
        return el;
    };
    u.before = function(el, html){
        if(!u.isElement(el)){
            console.warn('$api.before Function need el param, el param must be DOM Element');
            return;
        }
        el.insertAdjacentHTML('beforebegin', html);
        return el;
    };
    u.after = function(el, html){
        if(!u.isElement(el)){
            console.warn('$api.after Function need el param, el param must be DOM Element');
            return;
        }
        el.insertAdjacentHTML('afterend', html);
        return el;
    };
    u.html = function(el, html){
        if(!u.isElement(el)){
            console.warn('$api.html Function need el param, el param must be DOM Element');
            return;
        }
        if(arguments.length === 1){
            return el.innerHTML;
        }else if(arguments.length === 2){
            el.innerHTML = html;
            return el;
        }
    };
    u.text = function(el, txt){
        if(!u.isElement(el)){
            console.warn('$api.text Function need el param, el param must be DOM Element');
            return;
        }
        if(arguments.length === 1){
            return el.textContent;
        }else if(arguments.length === 2){
            el.textContent = txt;
            return el;
        }
    };
    u.offset = function(el){
        if(!u.isElement(el)){
            console.warn('$api.offset Function need el param, el param must be DOM Element');
            return;
        }
        var sl = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);
        var st = Math.max(document.documentElement.scrollTop, document.body.scrollTop);

        var rect = el.getBoundingClientRect();
        return {
            l: rect.left + sl,
            t: rect.top + st,
            w: el.offsetWidth,
            h: el.offsetHeight
        };
    };
    u.css = function(el, css){
        if(!u.isElement(el)){
            console.warn('$api.css Function need el param, el param must be DOM Element');
            return;
        }
        if(typeof css == 'string' && css.indexOf(':') > 0){
            el.style && (el.style.cssText += ';' + css);
        }
    };
    u.cssVal = function(el, prop){
        if(!u.isElement(el)){
            console.warn('$api.cssVal Function need el param, el param must be DOM Element');
            return;
        }
        if(arguments.length === 2){
            var computedStyle = window.getComputedStyle(el, null);
            return computedStyle.getPropertyValue(prop);
        }
    };
    u.jsonToStr = function(json){
        if(typeof json === 'object'){
            return JSON && JSON.stringify(json);
        }
    };
    u.strToJson = function(str){
        if(typeof str === 'string'){
            return JSON && JSON.parse(str);
        }
    };
    u.setStorage = function(key, value){
        if(arguments.length === 2){
            var v = value;
            if(typeof v == 'object'){
                v = JSON.stringify(v);
                v = 'obj-'+ v;
            }else{
                v = 'str-'+ v;
            }
            var ls = uzStorage();
            if(ls){
                ls.setItem(key, v);
            }
        }
    };
    u.getStorage = function(key){
        var ls = uzStorage();
        if(ls){
            var v = ls.getItem(key);
            if(!v){return;}
            if(v.indexOf('obj-') === 0){
                v = v.slice(4);
                return JSON.parse(v);
            }else if(v.indexOf('str-') === 0){
                return v.slice(4);
            }
        }
    };
    u.rmStorage = function(key){
        var ls = uzStorage();
        if(ls && key){
            ls.removeItem(key);
        }
    };
    u.clearStorage = function(){
        var ls = uzStorage();
        if(ls){
            ls.clear();
        }
    };
    u.fixIos7Bar = function(el){
        return u.fixStatusBar(el);
    };
    u.fixStatusBar = function(el){
        if(!u.isElement(el)){
            console.warn('$api.fixStatusBar Function need el param, el param must be DOM Element');
            return 0;
        }
        el.style.paddingTop = api.safeArea.top + 'px';
        return el.offsetHeight;
    };
    u.fixTabBar = function(el){
        if(!u.isElement(el)){
            console.warn('$api.fixTabBar Function need el param, el param must be DOM Element');
            return 0;
        }
        el.style.paddingBottom = api.safeArea.bottom + 'px';
        return el.offsetHeight;
    };
    u.toast = function(title, text, time){
        var opts = {};
        var show = function(opts, time){
            api.showProgress(opts);
            setTimeout(function(){
                api.hideProgress();
            },time);
        };
        if(arguments.length === 1){
            var time = time || 500;
            if(typeof title === 'number'){
                time = title;
            }else{
                opts.title = title+'';
            }
            show(opts, time);
        }else if(arguments.length === 2){
            var time = time || 500;
            var text = text;
            if(typeof text === "number"){
                var tmp = text;
                time = tmp;
                text = null;
            }
            if(title){
                opts.title = title;
            }
            if(text){
                opts.text = text;
            }
            show(opts, time);
        }
        if(title){
            opts.title = title;
        }
        if(text){
            opts.text = text;
        }
        time = time || 500;
        show(opts, time);
    };
    u.post = function(/*url,data,fnSuc,dataType*/){
        var argsToJson = parseArguments.apply(null, arguments);
        var json = {};
        var fnSuc = argsToJson.fnSuc;
        argsToJson.url && (json.url = argsToJson.url);
        argsToJson.data && (json.data = argsToJson.data);
        if(argsToJson.dataType){
            var type = argsToJson.dataType.toLowerCase();
            if (type == 'text'||type == 'json') {
                json.dataType = type;
            }
        }else{
            json.dataType = 'json';
        }
        json.method = 'post';
        api.ajax(json,
            function(ret,err){
                if (ret) {
                    fnSuc && fnSuc(ret);
                }
            }
        );
    };
    u.get = function(/*url,fnSuc,dataType*/){
        var argsToJson = parseArguments.apply(null, arguments);
        var json = {};
        var fnSuc = argsToJson.fnSuc;
        argsToJson.url && (json.url = argsToJson.url);
        //argsToJson.data && (json.data = argsToJson.data);
        if(argsToJson.dataType){
            var type = argsToJson.dataType.toLowerCase();
            if (type == 'text'||type == 'json') {
                json.dataType = type;
            }
        }else{
            json.dataType = 'text';
        }
        json.method = 'get';
        api.ajax(json,
            function(ret,err){
                if (ret) {
                    fnSuc && fnSuc(ret);
                }
            }
        );
    };

/*end*/
    

    window.$api = u;

})(window);


完整代码下载地址:https://download.csdn.net/download/weixin_41937552/13991075

本文地址:https://blog.csdn.net/weixin_41937552/article/details/112004275