一、日期
function pluralize(time, label) {
if (time === 1) {
return time + label
}
return time + label + 's'
}
export function dateFormat(date) {
let format = 'yyyy-MM-dd hh:mm:ss';
if (date != 'Invalid Date') {
var o = {
"M+": date.getMonth() + 1,
"d+": date.getDate(),
"h+": date.getHours(),
"m+": date.getMinutes(),
"s+": date.getSeconds(),
"q+": Math.floor((date.getMonth() + 3) / 3),
"S": date.getMilliseconds()
}
if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
(date.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(format))
format = format.replace(RegExp.$1,
RegExp.$1.length == 1 ? o[k] :
("00" + o[k]).substr(("" + o[k]).length));
return format;
}
return '';
}
export function timeAgo(time) {
const between = Date.now() / 1000 - Number(time)
if (between < 3600) {
return pluralize(~~(between / 60), ' minute')
} else if (between < 86400) {
return pluralize(~~(between / 3600), ' hour')
} else {
return pluralize(~~(between / 86400), ' day')
}
}
export function parseTime(time, cFormat) {
if (arguments.length === 0) {
return null
}
if ((time + '').length === 10) {
time = +time * 1000
}
const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
let date
if (typeof time === 'object') {
date = time
} else {
date = new Date(parseInt(time))
}
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
}
const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
let value = formatObj[key]
if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
if (result.length > 0 && value < 10) {
value = '0' + value
}
return value || 0
})
return time_str
}
export function formatTime(time, option) {
time = +time * 1000
const d = new Date(time)
const now = Date.now()
const diff = (now - d) / 1000
if (diff < 30) {
return '刚刚'
} else if (diff < 3600) {
return Math.ceil(diff / 60) + '分钟前'
} else if (diff < 3600 * 24) {
return Math.ceil(diff / 3600) + '小时前'
} else if (diff < 3600 * 24 * 2) {
return '1天前'
}
if (option) {
return parseTime(time, option)
} else {
return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
}
}
export function nFormatter(num, digits) {
const si = [
{ value: 1E18, symbol: 'E' },
{ value: 1E15, symbol: 'P' },
{ value: 1E12, symbol: 'T' },
{ value: 1E9, symbol: 'G' },
{ value: 1E6, symbol: 'M' },
{ value: 1E3, symbol: 'k' }
]
for (let i = 0; i < si.length; i++) {
if (num >= si[i].value) {
return (num / si[i].value + 0.1).toFixed(digits).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, '$1') + si[i].symbol
}
}
return num.toString()
}
export function html2Text(val) {
const div = document.createElement('div')
div.innerHTML = val
return div.textContent || div.innerText
}
export function toThousandslsFilter(num) {
return (+num || 0).toString().replace(/^-?\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ','))
}
export const calcDate = (date1, date2) => {
var date3 = date2 - date1;
var days = Math.floor(date3 / (24 * 3600 * 1000))
var leave1 = date3 % (24 * 3600 * 1000)
var hours = Math.floor(leave1 / (3600 * 1000))
var leave2 = leave1 % (3600 * 1000)
var minutes = Math.floor(leave2 / (60 * 1000))
var leave3 = leave2 % (60 * 1000)
var seconds = Math.round(date3 / 1000)
return {
leave1,
leave2,
leave3,
days: days,
hours: hours,
minutes: minutes,
seconds: seconds,
}
}
二、屏幕设置判断
export default {
getScreen: function() {
var width = document.body.clientWidth;
if (width >= 1200) {
return 3;
} else if (width >= 992) {
return 2;
} else if (width >= 768) {
return 1;
} else {
return 0;
}
}
}
三、文件工具类
export const getFileSuffix = (filename)=> {
if(filename){
let index = filename.lastIndexOf(".");
let suffix = filename.substr(index+1);
return suffix.toLowerCase();
}
return null;
};
四、操作Local Storage工具类
export const setStore = (params) => {
let {
name,
content,
type,
} = params;
let obj = {
dataType: typeof(content),
content: content,
type: type,
datetime: new Date().getTime()
}
if (type) window.sessionStorage.setItem(name, JSON.stringify(obj));
else window.localStorage.setItem(name, JSON.stringify(obj));
}
export const getStore = (params) => {
let {
name,
debug
} = params;
let obj = {},
content;
obj = window.sessionStorage.getItem(name);
if (validatenull(obj)) obj = window.localStorage.getItem(name);
if (validatenull(obj)) return;
obj = JSON.parse(obj);
if (debug) {
return obj;
}
if (obj.dataType == 'string') {
content = obj.content;
} else if (obj.dataType == 'number') {
content = Number(obj.content);
} else if (obj.dataType == 'boolean') {
content = eval(obj.content);
} else if (obj.dataType == 'object') {
content = obj.content;
}
return content;
}
export const removeStore = params => {
let {
name
} = params;
window.localStorage.removeItem(name);
window.sessionStorage.removeItem(name);
}
export const getAllStore = (params) => {
let list = [];
let {
type
} = params;
for (let i = 1; i <= window.sessionStorage.length; i++) {
if (type) {
list.push({
name: window.sessionStorage.key(i),
content: getStore({
name: window.sessionStorage.key(i),
type: 'session'
})
})
} else {
list.push(getStore({
name: window.localStorage.key(i),
content: getStore({
name: window.localStorage.key(i),
})
}))
}
}
return list;
}
export const clearStore = (params) => {
let {
type
} = params;
if (type) {
window.sessionStorage.clear();
return
}
window.localStorage.clear()
}
五、浏览器相关判断、深拷贝、表单序列化等
export const serialize = data => {
let list = [];
Object.keys(data).forEach(ele => {
list.push(`${ele}=${data[ele]}`)
})
return list.join('&');
};
export const getObjType = obj => {
var toString = Object.prototype.toString;
var map = {
'[object Boolean]': 'boolean',
'[object Number]': 'number',
'[object String]': 'string',
'[object Function]': 'function',
'[object Array]': 'array',
'[object Date]': 'date',
'[object RegExp]': 'regExp',
'[object Undefined]': 'undefined',
'[object Null]': 'null',
'[object Object]': 'object'
};
if (obj instanceof Element) {
return 'element';
}
return map[toString.call(obj)];
};
export const deepClone = data => {
var type = getObjType(data);
var obj;
if (type === 'array') {
obj = [];
} else if (type === 'object') {
obj = {};
} else {
return data;
}
if (type === 'array') {
for (var i = 0, len = data.length; i < len; i++) {
obj.push(deepClone(data[i]));
}
} else if (type === 'object') {
for (var key in data) {
obj[key] = deepClone(data[key]);
}
}
return obj;
};
export const toggleGrayMode = (status) => {
if (status) {
document.body.className = document.body.className + ' grayMode';
} else {
document.body.className = document.body.className.replace(' grayMode', '');
}
};
export const setTheme = (name) => {
document.body.className = name;
};
export const encryption = (params) => {
let {
data,
type,
param,
key
} = params;
let result = JSON.parse(JSON.stringify(data));
if (type === 'Base64') {
param.forEach(ele => {
result[ele] = btoa(result[ele]);
})
} else if (type === 'Aes') {
param.forEach(ele => {
result[ele] = window.CryptoJS.AES.encrypt(result[ele], key).toString();
})
}
return result;
};
export const fullscreenToggel = () => {
if (fullscreenEnable()) {
exitFullScreen();
} else {
reqFullScreen();
}
};
export const listenfullscreen = (callback) => {
function listen() {
callback()
}
document.addEventListener("fullscreenchange", function() {
listen();
});
document.addEventListener("mozfullscreenchange", function() {
listen();
});
document.addEventListener("webkitfullscreenchange", function() {
listen();
});
document.addEventListener("msfullscreenchange", function() {
listen();
});
};
export const fullscreenEnable = () => {
var isFullscreen = document.fullscreenEnabled ||
window.fullScreen ||
document.mozFullscreenEnabled ||
document.webkitIsFullScreen;
return isFullscreen;
}
export const reqFullScreen = () => {
if (document.documentElement.requestFullScreen) {
document.documentElement.requestFullScreen();
} else if (document.documentElement.webkitRequestFullScreen) {
document.documentElement.webkitRequestFullScreen();
} else if (document.documentElement.mozRequestFullScreen) {
document.documentElement.mozRequestFullScreen();
}
};
export const exitFullScreen = () => {
if (document.documentElement.requestFullScreen) {
document.exitFullScreen();
} else if (document.documentElement.webkitRequestFullScreen) {
document.webkitCancelFullScreen();
} else if (document.documentElement.mozRequestFullScreen) {
document.mozCancelFullScreen();
}
};
export const findParent = (menu, id) => {
for (let i = 0; i < menu.length; i++) {
if (menu[i].children.length != 0) {
for (let j = 0; j < menu[i].children.length; j++) {
if (menu[i].children[j].id == id) {
return menu[i];
} else {
if (menu[i].children[j].children.length != 0) {
return findParent(menu[i].children[j].children, id);
}
}
}
}
}
};
export const loadStyle = url => {
const link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = url;
const head = document.getElementsByTagName('head')[0];
head.appendChild(link);
};
export const diff = (obj1, obj2) => {
delete obj1.close;
var o1 = obj1 instanceof Object;
var o2 = obj2 instanceof Object;
if (!o1 || !o2) {
return obj1 === obj2;
}
if (Object.keys(obj1).length !== Object.keys(obj2).length) {
return false;
}
for (var attr in obj1) {
var t1 = obj1[attr] instanceof Object;
var t2 = obj2[attr] instanceof Object;
if (t1 && t2) {
return diff(obj1[attr], obj2[attr]);
} else if (obj1[attr] !== obj2[attr]) {
return false;
}
}
return true;
}
export const findByvalue = (dic, value) => {
let result = '';
if (validatenull(dic)) return value;
if (typeof(value) == 'string' || typeof(value) == 'number' || typeof(value) == 'boolean') {
let index = 0;
index = findArray(dic, value);
if (index != -1) {
result = dic[index].label;
} else {
result = value;
}
} else if (value instanceof Array) {
result = [];
let index = 0;
value.forEach(ele => {
index = findArray(dic, ele);
if (index != -1) {
result.push(dic[index].label);
} else {
result.push(value);
}
});
result = result.toString();
}
return result;
};
export const findArray = (dic, value) => {
for (let i = 0; i < dic.length; i++) {
if (dic[i].value == value) {
return i;
}
}
return -1;
};
export const randomLenNum = (len, date) => {
let random = '';
random = Math.ceil(Math.random() * 100000000000000).toString().substr(0, len ? len : 4);
if (date) random = random + Date.now();
return random;
};
export const openWindow = (url, title, w, h) => {
const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left
const dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top
const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width
const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height
const left = ((width / 2) - (w / 2)) + dualScreenLeft
const top = ((height / 2) - (h / 2)) + dualScreenTop
const newWindow = window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left)
if (window.focus) {
newWindow.focus()
}
}
六、常用校验工具类
export function isvalidUsername(str) {
const valid_map = ['admin', 'editor']
return valid_map.indexOf(str.trim()) >= 0
}
export function validateURL(textval) {
const urlregex = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
return urlregex.test(textval)
}
export function isEmail(s) {
return /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(s)
}
export function isMobile(s) {
return /^1[0-9]{10}$/.test(s)
}
export function isPhone(s) {
return /^([0-9]{3,4}-)?[0-9]{7,8}$/.test(s)
}
export function isURL(s) {
return /^http[s]?:\/\/.*/.test(s)
}
export function validateLowerCase(str) {
const reg = /^[a-z]+$/
return reg.test(str)
}
export function validateUpperCase(str) {
const reg = /^[A-Z]+$/
return reg.test(str)
}
export function validatAlphabets(str) {
const reg = /^[A-Za-z]+$/
return reg.test(str)
}
export const vaildatePc = function() {
const userAgentInfo = navigator.userAgent;
const Agents = ["Android", "iPhone",
"SymbianOS", "Windows Phone",
"iPad", "iPod"
];
let flag = true;
for (var v = 0; v < Agents.length; v++) {
if (userAgentInfo.indexOf(Agents[v]) > 0) {
flag = false;
break;
}
}
return flag;
}
export function validateEmail(email) {
const re = /^(([^<>()\\[\]\\.,;:\s@"]+(\.[^<>()\\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return re.test(email)
}
export function cardid(code) {
let list = [];
let result = true;
let msg = '';
var city = {
11: "北京",
12: "天津",
13: "河北",
14: "山西",
15: "内蒙古",
21: "辽宁",
22: "吉林",
23: "黑龙江 ",
31: "上海",
32: "江苏",
33: "浙江",
34: "安徽",
35: "福建",
36: "江西",
37: "山东",
41: "河南",
42: "湖北 ",
43: "湖南",
44: "广东",
45: "广西",
46: "海南",
50: "重庆",
51: "四川",
52: "贵州",
53: "云南",
54: "西藏 ",
61: "陕西",
62: "甘肃",
63: "青海",
64: "宁夏",
65: "新疆",
71: "台湾",
81: "香港",
82: "澳门",
91: "国外 "
};
if (!validatenull(code)) {
if (code.length == 18) {
if (!code || !/(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(code)) {
msg = "证件号码格式错误";
} else if (!city[code.substr(0, 2)]) {
msg = "地址编码错误";
} else {
code = code.split('');
var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2, 'x'];
var sum = 0;
var ai = 0;
var wi = 0;
for (var i = 0; i < 17; i++) {
ai = code[i];
wi = factor[i];
sum += ai * wi;
}
if (parity[sum % 11] != code[17]) {
msg = "证件号码校验位错误";
} else {
result = false;
}
}
} else {
msg = "证件号码长度不为18位";
}
} else {
msg = "证件号码不能为空";
}
list.push(result);
list.push(msg);
return list;
}
export function isvalidatemobile(phone) {
let list = [];
let result = true;
let msg = '';
var isPhone = /^0\d{2,3}-?\d{7,8}$/;
if (!validatenull(phone)) {
if (phone.length == 11) {
if (isPhone.test(phone)) {
msg = '手机号码格式不正确';
} else {
result = false;
}
} else {
msg = '手机号码长度不为11位';
}
} else {
msg = '手机号码不能为空';
}
list.push(result);
list.push(msg);
return list;
}
export function validatename(name) {
var regName = /^[\u4e00-\u9fa5]{2,4}$/;
if (!regName.test(name)) return false;
return true;
}
export function validatenum(num, type) {
let regName = /[^\d.]/g;
if (type == 1) {
if (!regName.test(num)) return false;
} else if (type == 2) {
regName = /[^\d]/g;
if (!regName.test(num)) return false;
}
return true;
}
export function validatenumord(num, type) {
let regName = /[^\d.]/g;
if (type == 1) {
if (!regName.test(num)) return false;
} else if (type == 2) {
regName = /[^\d.]/g;
if (!regName.test(num)) return false;
}
return true;
}
export function validatenull(val) {
if (typeof val == 'boolean') {
return false;
}
if (typeof val == 'number') {
return false;
}
if (val instanceof Array) {
if (val.length == 0) return true;
} else if (val instanceof Object) {
if (JSON.stringify(val) === '{}') return true;
} else {
if (val == 'null' || val == null || val == 'undefined' || val == undefined || val == '') return true;
return false;
}
return false;
}
七、操作IndexedDB
!function(e, o) {
"function" == typeof define && define.amd ? define([], o) : "object" == typeof exports ? module.exports = o() : e.IndexedDB = o()
} (this,
function() {
var e = function(e) {
var o;
if (e.keyNames) {
o = e.keyNames;
for (var n = 0; n < o.length; n++) o[n].unique || (o[n].unique = !1)
}
this.dbName = e.dbName,
this.version = e.version,
this.primaryKey = e.primaryKey || "id",
this.keyNames = e.keyNames,
this.db = null,
this.allData = []
};
return e.prototype = {
init: function() {
var o = this,
n = o.dbName,
e = o.version,
r = o.primaryKey,
a = o.keyNames;
if (! (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB)) return window.alert("您的浏览器不支持当前内容"),
!1;
if (!n) return window.alert("数据库名称不能为空"),
!1;
var t = window.indexedDB.open(n, e);
t.onsuccess = function(e) {
o.db = t.result
},
t.onerror = function(e) {
window.alert("数据库打开失败")
},
t.onupgradeneeded = function(e) {
if (o.db = e.target.result, o.db.onerror = function(e) {
window.alert("数据库打开失败")
},
!o.db.objectStoreNames.contains(n)) var t = o.db.createObjectStore(n, {
keyPath: r,
autoIncrement: !0
});
a.forEach(function(e, o, n) {
t.createIndex(e.key, e.key, {
unique: e.unique || !1
})
})
}
},
set: function(e) {
var o = this,
n = o.dbName,
t = (o.version, o.db),
r = (o.primaryKey, o.keyNames, t.transaction([n], "readwrite")),
a = r.objectStore(n);
if (Array.isArray(e)) for (var i = 0; i < e.length; i++) a.add(e[i]).onsuccess = function(e) {
console.log("数据写入成功")
},
r.onerror = function(e) {
console.log("数据库中已有该数据")
};
else a.add(e).onsuccess = function(e) {
console.log("数据写入成功")
},
r.onerror = function(e) {
console.log("数据库中已有该数据")
}
},
updateData: function(e) {
var o = this.dbName,
n = this.db.transaction([o], "readwrite"),
t = n.objectStore(o);
if (Array.isArray(e)) for (var r = 0; r < e.length; r++) t.put(e[r]).onsuccess = function(e) {
console.log("数据更新成功")
},
n.onerror = function(e) {
console.log("数据更新成功")
};
else t.put(e).onsuccess = function(e) {
console.log("数据更新成功")
},
n.onerror = function(e) {
console.log("数据更新成功")
}
},
getAllData: function() {
var n = this,
e = n.dbName;
return n.allData = [],
n.db.transaction(e).objectStore(e).openCursor().onsuccess = function(e) {
var o = e.target.result;
o && (console.log(o.value), n.allData.push(o.value), o.
continue ())
},
n.allData
},
getData: function(e) {
var o = this.dbName,
n = this.db.transaction(o).objectStore(o).get(e);
n.onerror = function(e) {
console.log("获取失败")
},
n.onsuccess = function(e) {
if (n.result) return console.log(n.result),
n.result;
console.log("未获得数据记录")
}
},
deleteDB: function() {
var e = this.dbName;
window.indexedDB.deleteDatabase(e),
console.log(e + "数据库已删除")
},
closeDB: function() {
this.db.close(),
console.log("数据库已关闭")
},
deleteData: function(e) {
var o = this.dbName;
this.db.transaction(o, "readwrite").objectStore(o).delete(e).onsuccess = function(e) {
console.log("删除成功")
}
},
clearData: function() {
var e = this.dbName;
this.db.transaction(e, "readwrite").objectStore(e).clear(),
console.log("已删除存储空间" + e + "全部记录")
},
searchData: function(e, o) {
var n = this.dbName,
t = this.db.transaction(n, "readonly").objectStore(n).index(e).get(o);
t.onerror = function() {
return console.error("搜索出错"),
!1
},
t.onsuccess = function(e) {
var o = e.target.result;
return o ? (console.log(o), o) : (console.log("您搜索的数据不存在"), !1)
}
}
},
e
});