1.获取URL中所传的参数中的值
function getQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null)
return unescape(r[2]);
return null;
}
2. 60秒倒计时函数
function codeButton() {
var code = $("#code");
code.attr("disabled", "disabled");
setTimeout(function() {
code.css("opacity", "0.8");
}, 1000)
var time = 60;
var set = setInterval(function() {
code.val("(" + --time + ")秒后重新获取");
}, 1000);
setTimeout(function() {
code.attr("disabled", false).val("重新获取验证码");
clearInterval(set);
}, 60000);
}
3.判断当月总天数的函数
function getDay(year, month) {
var days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
//如果是润年
if (year % 4 == 0 && (year % 400 == 0 || year % 100 != 0)) {
days[1] == 29;
}
return days[month];
}
4.获取当前时间,格式YYYY-MM-DD
function getNowFormatDate() {
var date = new Date();
var seperator1 = "-";
var year = date.getFullYear();
var month = date.getMonth() + 1;
var strDate = date.getDate(); //
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
var currentdate = year + seperator1 + month + seperator1 + strDate;
return currentdate;
}
5.获取当前时间格式 2021-11-25 18:51:58
function getNowFormatDate() {
var date = new Date();
var seperator1 = "-";
var year = date.getFullYear();
var month = date.getMonth() + 1;
var strDate = date.getDate();
let hou = date.getHours(); // 获取当前小时数(0-23)
let min = date.getMinutes(); // 获取当前分钟数(0-59)
let sin = date.getSeconds(); // 获取当前分钟数(0-59)
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
if (hou >= 0 && hou <= 9) {
hou = "0" + hou;
}
if (min >= 0 && min <= 9) {
min = "0" + min;
}
if (sin >= 0 && sin <= 9) {
sin = "0" + sin;
}
var currentdate = year + seperator1 + month + seperator1 + strDate +" " +hou+":"+min+":"+sin;
return currentdate;
},
6.获取当前时间往前推n天的日期,格式YYYY-MM-DD
function getBeforeDate(n) {
var n = n;
var d = new Date();
var year = d.getFullYear();
var mon = d.getMonth() + 1;
var day = d.getDate();
if (day <= n) {
if (mon > 1) {
mon = mon - 1;
} else {
year = year - 1;
mon = 12;
}
}
d.setDate(d.getDate() - n);
year = d.getFullYear();
mon = d.getMonth() + 1;
day = d.getDate();
s = year + "-" + (mon < 10 ? ('0' + mon) : mon) + "-" + (day < 10 ? ('0' + day) : day);
return s;
}
7.计算两个日期间有几天
function getDiffDate(dateString1, dateString2) {
var startDate = Date.parse(dateString1.replace('/-/g', '/'));
var endDate = Date.parse(dateString2.replace('/-/g', '/'));
var diffDate = (endDate - startDate) + 1 * 24 * 60 * 60 * 1000;
var days = diffDate / (1 * 24 * 60 * 60 * 1000);
//alert(diffDate/(1*24*60*60*1000));
return days;
}
8.生成区间随机数
function randombetween(min, max) {
return min + (Math.random() * (max - min + 1));
}
9.处理input中的空白字符串
function inputValue(text) {
var _val = text.replace(/^(\s|\u00A0)+/, '').replace(/(\s|\u00A0)+$/, '');
return _val;
}
10.判断开始时间不能大于结束时间
function time_size(start_time, end_time) {
var start_time = new Date(start_time.replace(/\-/g, "\/"));
var end_time = new Date(end_time.replace(/\-/g, "\/"));
if (start_time > end_time) {
alert('开始时间不能大于结束时间')
}
}
11.随机生成颜色值
随机生成颜色值
又是美好的一天
12.校验密码:只能输入6-20个字母、数字、下划线
function isPasswd(s) {
var patrn = /^(\w){6,20}$/;
if (!patrn.exec(s)) return false
return true
}
13. 获取域名主机 params: url:域名
function getHost(url) {
var host = "null";
if (typeof url == "undefined" || null == url) {
url = window.location.href;
}
var regex = /^\w+\:\/\/([^\/]*).*/;
var match = url.match(regex);
if (typeof match != "undefined" && null != match) {
host = match[1];
}
return host;
}
14. cookie相关操作
// 设置cookie
function setCookie(name, value) {
const Days = 30; //一个月
let exp = new Date();
exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
document.cookie =
name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}
// 获取cookie
function getCookie(name) {
let arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
if (arr != null) {
return arr[2];
} else {
return "";
}
}
// 删除cookie
function delCookie(name) {
let exp = new Date();
exp.setTime(exp.getTime() - 1);
let cval = getCookie(name);
if (cval != null) {
document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}
}
15.本地存储相关操作
// 设置sessionStorage 保存后浏览器关闭值即消失
function setSessionStorage(key, value) {
if (window.sessionStorage) {
window.sessionStorage.setItem(key, window.JSON.stringify(value));
}
},
// 获取sessionStorage
function getSessionStorage(key) {
var json = "";
if (window.sessionStorage) {
json = window.sessionStorage.getItem(key);
}
return window.JSON.parse(json);
},
// 删除sessionStorage
function deleteItem() {
sessionStorage.removeItem('userinfo');
console.log(sessionStorage.getItem('userinfo'));
}
// 设置localStorage 保存后永久有效
function setLocalStorage(key, value) {
if (window.localStorage) {
window.localStorage.setItem(key, window.JSON.stringify(value));
}
},
// 获取localStorage
function getLocalStorage(key) {
var json = "";
if (window.localStorage) {
json = window.localStorage.getItem(key);
}
return window.JSON.parse(json);
},
// 删除localStorage
function deleteItem() {
localStorage.removeItem('userinfo');
console.log(localStorage.getItem('userinfo'));
}
16.时间倒计时
function getEndTime(endTime) {
var startDate = new Date(); //开始时间,当前时间
var endDate = new Date(endTime); //结束时间,需传入时间参数
var t = endDate.getTime() - startDate.getTime(); //时间差的毫秒数
var d = 0,
h = 0,
m = 0,
s = 0;
if (t >= 0) {
d = Math.floor(t / 1000 / 3600 / 24);
h = Math.floor((t / 1000 / 60 / 60) % 24);
m = Math.floor((t / 1000 / 60) % 60);
s = Math.floor((t / 1000) % 60);
}
return "剩余时间" + d + "天 " + h + "小时 " + m + " 分钟" + s + " 秒";
}
17.移动端自适应rem单位
function getFontSize(_client) {
var doc = document,
win = window;
var docEl = doc.documentElement,
resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
recalc = function() {
var clientWidth = docEl.clientWidth;
if (!clientWidth) return;
//如果屏幕大于750(750是根据我效果图设置的,具体数值参考效果图),就设置clientWidth=750,防止font-size会超过100px
if (clientWidth > _client) {
clientWidth = _client
}
//设置根元素font-size大小
docEl.style.fontSize = 100 * (clientWidth / _client) + 'px';
};
//屏幕大小改变,或者横竖屏切换时,触发函数
win.addEventListener(resizeEvt, recalc, false);
//文档加载完成时,触发函数
doc.addEventListener('DOMContentLoaded', recalc, false);
},
18.清除字符串前后的空格
function trim(s){
return s.replace(/(^\s*)|(\s*$)/g, "");
}
19.把任意时间格式转换成('2019-08-20')格式
function parseTime(time, cFormat) {
if (arguments.length === 0) {
return null
}
const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
let date
if (typeof time === 'object') {
date = time
} else {
if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
time = parseInt(time)
}
if ((typeof time === 'number') && (time.toString().length === 10)) {
time = time * 1000
}
date = new Date(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]
// Note: getDay() returns 0 on Sunday
if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
if (result.length > 0 && value < 10) {
value = '0' + value
}
return value || 0
})
return time_str
}
调用案例:
var time = new Date()
parseTime(time ,'{yyyy}-{mm}-{dd}')
20.将普通json数据格式化成tree类型数据
function transTree(data) {
let result = [];
let map = {};
if (!Array.isArray(data)) {
return [];
}
data.forEach((item) => {
map[item.id] = item;
delete item.children;
});
data.forEach((item) => {
let parent = map[item.pid];//pid可根据后台返回自己定义
if (parent) {
(parent.children || (parent.children = [])).push(item);
} else {
result.push(item);
}
});
console.log(result)
return result;
}
21.递归遍历json树结构数据
function setName(datas){ //遍历树 获取id数组
let arr = []
for(let i in datas){
if(datas[i].show){// 遍历项目满足条件后的操作
arr.push(datas[i].id)
}
if(datas[i].children){ //存在子节点就递归
for(let n in datas[i].children){
if(datas[i].children[n].show){
arr.push(datas[i].children[n].id)
}
this.setName(datas[i].children);
}
}
}
return arr
},
22.文字替代(添加css样式)
function changeText(name) {
return name.replace(this.searchName, `${this.searchName}`);
}
23.获取用户guid
function Guid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
23. 遍历原数据转换成json树结构数据
function setName(datas){ //遍历树 获取id数组
let codeMap = {};
let treeList = [] ;
datas.forEach((item, i) => {
codeMap[item.id] = item;
let parentNode = codeMap[item.parent];
if (parentNode) {
if (parentNode.children && parentNode.children.length > 0) {
parentNode.children.push(item);
}else {
parentNode["children"] = [item];
}
} else {
treeList.push(item);
}
});
return treeList
}
24. 根据条件递归循环筛选树结构数据
getCurrentMenu(dataList, roleList){
let menu = dataList.filter(item =>{
console.log(roleList.indexOf(item.name) !== -1)
if(roleList.indexOf(item.name) !== -1){
if(item.children){
//递归循环
item.children=getCurrentMenu(item.children,roleList)
}
return item
}
})
return menu
}
25. base64图片缓存到本地,返回本地路径
/**
* base64图片缓存到本地,返回本地路径
* */
function base64ToPath(base64) {
return new Promise(function (resolve, reject) {
if (typeof window === 'object' && 'document' in window) {
base64 = base64.split(',')
var type = base64[0].match(/:(.*?);/)[1]
var str = atob(base64[1])
var n = str.length
var array = new Uint8Array(n)
while (n--) {
array[n] = str.charCodeAt(n)
}
return resolve((window.URL || window.webkitURL).createObjectURL(new Blob([array], {
type: type
})))
}
var extName = base64.match(/data\:\S+\/(\S+);/)
if (extName) {
extName = extName[1]
} else {
reject(new Error('base64 error'))
}
var fileName = Date.now() + '.' + extName
if (typeof plus === 'object') {
var bitmap = new plus.nativeObj.Bitmap('bitmap' + Date.now())
bitmap.loadBase64Data(base64, function () {
var filePath = '_doc/uniapp_temp/' + fileName
bitmap.save(filePath, {}, function () {
bitmap.clear()
resolve(filePath)
}, function (error) {
bitmap.clear()
reject(error)
})
}, function (error) {
bitmap.clear()
reject(error)
})
return
}
if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
var filePath = wx.env.USER_DATA_PATH + '/' + fileName
wx.getFileSystemManager().writeFile({
filePath: filePath,
data: base64.replace(/^data:\S+\/\S+;base64,/, ''),
encoding: 'base64',
success: function () {
resolve(filePath)
},
fail: function (error) {
reject(error)
}
})
return
}
reject(new Error('not support'))
})
}
26.文件下载
/**
* 文件下载
*
* @param {String} url 下载的路径
* @param {String} fileName 文件名称 带格式后缀
*
*/
function download (url, fileName) {
const link = document.createElement("a");
link.href =baseUrl + url; //基础路径+后台返回文件地址
link.target = "_blank";
link.download = fileName;
link.style.display = "none";
document.body.append(link);
link.click();
document.body.removeChild(link);
};
27.将base64转换成file对象
// 将base64转换成file对象
function dataURLtoFile (dataurl, filename = 'file') {
let arr = dataurl.split(',')
let mime = arr[0].match(/:(.*?);/)[1]
let suffix = mime.split('/')[1]
let bstr = atob(arr[1])
let n = bstr.length
let u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new File([u8arr], `${filename}.${suffix}`, {type: mime})
}
28.复制文本
//复制文本
copyText(data){
let url = data;//需要复制的文本
//新建一个文本框
let oInput = document.createElement('input');
//赋值给文本框
oInput.value = url;
document.body.appendChild(oInput);
// 选择对象;
oInput.select();
// 执行浏览器复制命令
document.execCommand("Copy");
//复制完成删除掉输入框
oInput.remove()
console.log('复制成功')
}