接口介绍
使用构造函数法定义一个接口模拟类,在内部用this关键字指代实例对象,使用prototype对象添加类的属性和方法。
原文链接:Caiqm的笔记
1. 新建api.js文件,同时定义一个接口模拟类,从第二步开始为添加类方法
/**
* 接口模拟类
* @constructor
*/
function Api() {
this.appVersion = '1.0.1';
this.description = 'js常用方法归类';
}
2. 简单输出信息
/**
* 输出信息
* @param arg 要输出的内容
*/
Api.prototype.console = function (arg) {
console.log(arg);
};
3. 设置页面标题
/**
* 设置页面标题
* @param title 更换标题
*/
Api.prototype.setNavigationTitle = function (title) {
let titleTag = document.getElementsByTagName('title')[0];
titleTag.innerText = title;
};
4. 页面跳转
/**
* 页面跳转
* @param url 跳转的链接
* @param time 跳转等待的时间
*/
Api.prototype.hrefTo = function (url, time) {
if (time === 0) {
window.location.href = url;
} else {
setTimeout("api.hrefTo('" + url + "', 0)", time);
}
};
5. 土司弹框
/**
* 土司弹框
* @param msg 提示内容
* @param duration 提示时间
*/
Api.prototype.toast = function (msg, duration) {
// 检测是手机或者PC
let sUserAgent = navigator.userAgent.toLowerCase();
let bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
let bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
let bIsMidp = sUserAgent.match(/midp/i) == "midp";
let bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
let bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
let bIsAndroid = sUserAgent.match(/android/i) == "android";
let bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
let bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
let box = '';
if (!(bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) ){
box = {width: '60%', height: '35px', fontsize: '12px', padding: '0 10px'};
} else {
box = {width: '80%', height: '75px', fontsize: '35px', padding: '0 20px'};
}
duration = isNaN(duration) ? 1500 : duration;
let m = document.createElement('div');
let m_span = document.createElement('span');
m.appendChild(m_span);
m.style.cssText = "width: 100%;position: absolute;top: 60%;right: 0;bottom: 0;left: 0;margin: auto;";
m_span.style.cssText = "max-width: "+box.width+";display: table;margin: 0 auto;padding: "+ box.padding +";box-sizing: border-box;opacity: 0.5;overflow: hidden;height: "+box.height+";color: rgb(255, 255, 255);line-height: "+box.height+";text-align: center;border-radius: 5px;z-index: 9999;background: rgb(0, 0, 0);font-size: "+box.fontsize+";";
m_span.innerHTML = msg;
document.body.appendChild(m);
setTimeout(function() {
let d = 0.5;
m.style.webkitTransition = '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in';
m.style.opacity = '0';
setTimeout(function() { document.body.removeChild(m) }, d * 1000);
}, duration);
};
6. 对话框弹框
/**
* 弹框
* @param object 对象信息
*/
Api.prototype.dialog = function (object) {
// 检测是手机或者PC
let sUserAgent = navigator.userAgent.toLowerCase();
let bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
let bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
let bIsMidp = sUserAgent.match(/midp/i) == "midp";
let bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
let bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
let bIsAndroid = sUserAgent.match(/android/i) == "android";
let bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
let bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
let box = '';
if (!(bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) ){
box = {width: '300px', height: '150px', fontsize: ''};
} else {
box = {width: '80%', height: '30%', fontsize: '40px'};
}
let cssText = "\n";
// 创建div
let m = document.createElement('div');
// 添加class名称
m.classList.add("dv_dialog_box");
let t = '';
t += ''+ (object.title ? object.title : '提示') +'';
t += ''+ (object.content ? object.content : '暂无数据') +'';
t += '';
// 判断是否显示取消按钮
if (object.showCancel && object.showCancel === true) {
t += '';
}
t += '';
t += '';
t += cssText;
m.innerHTML = t;
// 将弹框添加到body
document.body.appendChild(m);
// 获取按钮
let dialogBtn = document.getElementsByClassName('dialog_btn');
for (let i = 0; i < dialogBtn.length; i++) {
dialogBtn[i].onclick = function () {
// 清除掉弹框
document.body.removeChild(m);
// 确定按钮和取消按钮回调
if (object.showCancel && object.showCancel === true && i == 1 && object.callback) {
object.callback();
} else if (object.showCancel && object.showCancel === true && i == 0 && object.cancelCallback) {
object.cancelCallback();
} else if (!object.showCancel && i == 0 && object.callback) {
object.callback();
}
};
}
};
7. 输出当前时间或者更换输入时间分割符
/**
* 输出当前时间或者更换输入时间分割符
* @param date 时间字符串
* @param separate 日期分割符
* @returns {string}
*/
Api.prototype.formatTime = function (date, separate) {
// 时间判断
if (date) {
let dateSplit = date.split(/[^0-9]/);
date = new Date(dateSplit[0], dateSplit[1] - 1, dateSplit[2], dateSplit[3], dateSplit[4], dateSplit[5]);
} else {
date = new Date();
}
// 日期分割符
separate = separate ? separate : '/';
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hour = date.getHours();
const minute = date.getMinutes();
const second = date.getSeconds();
return [year, month, day].map(api.formatNumber).join(separate) + ' ' + [hour, minute, second].map(api.formatNumber).join(':');
};
8. 数字格式化,小于9补0
/**
* 数字格式化,小于9补0
* @param n 数字
* @returns {any}
*/
Api.prototype.formatNumber = function (n) {
n = n.toString();
return n[1] ? n : '0' + n
};
9. 时间倒计时
/**
* 倒计时
* @param expireTime 结束日期字符串
* @param marking 天数标识
* @returns {*}
*/
Api.prototype.countDown = function (expireTime, marking) {
// 转换日期格式
let a = expireTime.split(/[^0-9]/);
// 截止日期:日期转毫秒
let expireMs = new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
// 倒计时毫秒
let duringMs = expireMs.getTime() - (new Date()).getTime();
// 渲染倒计时时钟
let duringDate = '';
// 格式化日期,marking不存在显示“天时分秒”,否则显示“时分秒”
if (!marking) {
const days = api.formatNumber(parseInt(duringMs / 1000 / 60 / 60 / 24, 10)).toString(); //计算剩余的天数
const hours = api.formatNumber(parseInt(duringMs / 1000 / 60 / 60 % 24, 10)).toString(); //计算剩余的小时
const minutes = api.formatNumber(parseInt(duringMs / 1000 / 60 % 60, 10)).toString();//计算剩余的分钟
const seconds = api.formatNumber(parseInt(duringMs / 1000 % 60, 10)).toString();//计算剩余的秒数
duringDate = days + ":" + hours + ":" + minutes + ":" + seconds;
} else {
const hours = api.formatNumber(parseInt(duringMs / 1000 / 60 / 60, 10)).toString(); //计算剩余的小时
const minutes = api.formatNumber(parseInt(duringMs / 1000 / 60 % 60, 10)).toString();//计算剩余的分钟
const seconds = api.formatNumber(parseInt(duringMs / 1000 % 60, 10)).toString();//计算剩余的秒数
duringDate = hours + ":" + minutes + ":" + seconds;
}
// 判断是否已经结束
if (duringMs <= 0) {
// timeout则跳出递归
return '倒计时已完成';
}
// setTimeout(function () {
// // 放在最后--
// api.countDown(expireTime);
// }, 1000);
return duringDate;
};
10. 验证手机号码
/**
* 验证手机号码
* @param phone 手机号码
* @returns {boolean} 返回true|false
*/
Api.prototype.phoneVerify = function (phone) {
let reg = /^[1][3,4,5,6,7,8][0-9]{9}$/;
return reg.test(phone);
};
11. 验证邮箱
/**
* 验证邮箱
* @param email 邮箱地址
* @returns {boolean}
*/
Api.prototype.emailVerify = function (email) {
let reg = /^[a-z0-9][a-z\.0-9-_]+@[a-z0-9_-]+(?:\.[a-z]{0,3}\.[a-z]{0,2}|\.[a-z]{0,3}|\.[a-z]{0,2})$/i;
return reg.test(email);
};
12. 验证身份证
/**
* 验证身份证
* @param idcard 身份证号码
* @returns {boolean}
*/
Api.prototype.idcardVerify = function (idcard) {
let reg = /(^d{15}$)|(^d{17}([0-9]|X|x)$)/;
return reg.test(idcard);
};
13. 验证中文
/**
* 验证中文
* @param chinese
* @returns {boolean}
*/
Api.prototype.chineseVerify = function (chinese) {
let reg = /[u4e00-u9fa5]/;
return reg.test(chinese);
};
14. 添加新数组数据到旧数组
/**
* 添加新数据到旧数组
* @param orgArr 旧数组
* @param addFile 新数组
* @returns {*}
*/
Api.prototype.addNewToArr = function (orgArr, addFile) {
if (!addFile) {
return orgArr;
}
for (let i = 0; i < addFile.length; i++) {
orgArr.push(addFile[i]);
}
return orgArr;
};
15. 检测参数是否为空
/**
* 检测参数是否为空
* @param checkObj 检测对象内容
* @param showWord 提示文字
* @param isTip 提示方式
* @returns {boolean}
*/
Api.prototype.checkIsNull = function (checkObj, showWord, isTip) {
if (!checkObj) {
if (!isTip) {
api.dialog({ content: showWord });
} else {
api.toast(showWord);
}
return false;
}
return true;
};
16. 获取对象、数组的长度、元素长度个数
/**
* 获取对象、数组的长度、元素长度个数
* @param obj 要计算长度的元素,可以为object、array、string
* @returns {*}
*/
Api.prototype.getLength = function (obj) {
let objType = typeof obj;
if(objType === "string"){
return obj.length;
}else if(objType === "object"){
let objLen = 0;
for (let i in obj) {
objLen++;
}
return objLen;
}
return false;
};
17. 限制字符串长度(字节)
/**
* 字节限制字符串长度
* @param val 字符串
* @param max 最长个数
* @returns {string}
*/
Api.prototype.getByteVal = function (val, max) {
let returnValue = '';
let byteValLen = 0;
for (let i = 0; i < val.length; i++) {
if (val[i].match(/[^x00-xff]/ig) != null) {
byteValLen += 2;
} else {
byteValLen += 1;
}
if (byteValLen > max) {
break;
}
returnValue += val[i];
}
return returnValue;
};
18. 去除一维数组重复值
/**
* 去除一维数组重复值
* @param arr 去重数组
* @returns {Array}
*/
Api.prototype.unique = function (arr) {
let temp = [];
for (let i = 0; i < arr.length; i++) {
if (temp.indexOf(arr[i]) === -1) {
temp.push(arr[i]);
}
}
return temp;
};
19. 禁止移动端浏览器页面滚动
/**
* 禁止移动端浏览器页面滚动
*/
Api.prototype.stopBrowseScroll = function () {
document.addEventListener('touchmove', function(event) {
event.preventDefault();
});
};
20. 判断是否微信浏览器
/**
* 判断是否微信浏览器
* @returns {boolean}
*/
Api.prototype.isWeiXinClient = function () {
let ua = navigator.userAgent.toLowerCase();
return (ua.match(/MicroMessenger/i) == "micromessenger") ? true : false;
};
重要的一点是实例化类,不然调用不了定义的方法或属性
类实例化赋值
$api = api = new Api();
使用方法
标题
浏览器查看效果
目前归类的常用js方法有二十多种,可以放到一个.js文件进行使用。因为是通过原生javascript编辑,所以不需要引入JQuery文件,兼容PC和手机浏览器。
© 2018 All by Caiqm.