1.獲取URL中所傳的參數(shù)中的值
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秒倒計時函數(shù)
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.判斷當(dāng)月總天數(shù)的函數(shù)
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.獲取當(dāng)前時間,格式Y(jié)YYY-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.獲取當(dāng)前時間格式 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(); // 獲取當(dāng)前小時數(shù)(0-23)
let min = date.getMinutes(); // 獲取當(dāng)前分鐘數(shù)(0-59)
let sin = date.getSeconds(); // 獲取當(dāng)前分鐘數(shù)(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.獲取當(dāng)前時間往前推n天的日期,格式Y(jié)YYY-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.生成區(qū)間隨機數(shù)
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.判斷開始時間不能大于結(jié)束時間
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('開始時間不能大于結(jié)束時間')
}
}
11.隨機生成顏色值
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>隨機生成顏色值</title>
<style type="text/css">
.start{
width: 200px;
height: 200px;
background: #CCCCCC;
margin: 100px auto;
}
</style>
</head>
<body>
<div class="start">
<h1 class="title">又是美好的一天</h1>
</div>
</body>
<script type="text/javascript">
var title = document.querySelector('.title');
title.style.color = randomColor()
function randBack(){ //rgb顏色值 reg(255,0,256)
var r = Math.floor( Math.random() * 256 );
var g = Math.floor( Math.random() * 256 );
var b = Math.floor( Math.random() * 256 );
return "rgb("+r+','+g+','+b+")";
}
function randomColor(){ // 16進制顏色值 #ff9900
var colorValue = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f";
var colorArray = colorValue.split(",");
var color = "#";
for( var i = 0; i < 6; i++ ){
color += colorArray[ Math.floor( Math.random() * 16 ) ];
}
return color;
}
</script>
</html>
12.校驗密碼:只能輸入6-20個字母缩搅、數(shù)字、下劃線
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相關(guān)操作
// 設(shè)置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.本地存儲相關(guān)操作
// 設(shè)置sessionStorage 保存后瀏覽器關(guān)閉值即消失
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'));
}
// 設(shè)置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(); //開始時間拴念,當(dāng)前時間
var endDate = new Date(endTime); //結(jié)束時間,需傳入時間參數(shù)
var t = endDate.getTime() - startDate.getTime(); //時間差的毫秒數(shù)
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.移動端自適應(yīng)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是根據(jù)我效果圖設(shè)置的仗谆,具體數(shù)值參考效果圖),就設(shè)置clientWidth=750淑履,防止font-size會超過100px
if (clientWidth > _client) {
clientWidth = _client
}
//設(shè)置根元素font-size大小
docEl.style.fontSize = 100 * (clientWidth / _client) + 'px';
};
//屏幕大小改變隶垮,或者橫豎屏切換時,觸發(fā)函數(shù)
win.addEventListener(resizeEvt, recalc, false);
//文檔加載完成時秘噪,觸發(fā)函數(shù)
doc.addEventListener('DOMContentLoaded', recalc, false);
},
18.清除字符串前后的空格
function trim(s){
return s.replace(/(^\s*)|(\s*$)/g, "");
}
19.把任意時間格式轉(zhuǎn)換成('2019-08-20')格式
function parseTime(time, cFormat) {
if (arguments.length === 0) {
return null
}
const format = cFormat || '{y}-{m}-uf01feu {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
}
調(diào)用案例:
var time = new Date()
parseTime(time ,'{yyyy}-{mm}-{dd}')
20.將普通json數(shù)據(jù)格式化成tree類型數(shù)據(jù)
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可根據(jù)后臺返回自己定義
if (parent) {
(parent.children || (parent.children = [])).push(item);
} else {
result.push(item);
}
});
console.log(result)
return result;
}
21.遞歸遍歷json樹結(jié)構(gòu)數(shù)據(jù)
function setName(datas){ //遍歷樹 獲取id數(shù)組
let arr = []
for(let i in datas){
if(datas[i].show){// 遍歷項目滿足條件后的操作
arr.push(datas[i].id)
}
if(datas[i].children){ //存在子節(jié)點就遞歸
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, `<span style='color:#11CA7A;'>${this.searchName}</span>`);
}
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. 遍歷原數(shù)據(jù)轉(zhuǎn)換成json樹結(jié)構(gòu)數(shù)據(jù)
function setName(datas){ //遍歷樹 獲取id數(shù)組
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. 根據(jù)條件遞歸循環(huán)篩選樹結(jié)構(gòu)數(shù)據(jù)
getCurrentMenu(dataList, roleList){
let menu = dataList.filter(item =>{
console.log(roleList.indexOf(item.name) !== -1)
if(roleList.indexOf(item.name) !== -1){
if(item.children){
//遞歸循環(huán)
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; //基礎(chǔ)路徑+后臺返回文件地址
link.target = "_blank";
link.download = fileName;
link.style.display = "none";
document.body.append(link);
link.click();
document.body.removeChild(link);
};
27.將base64轉(zhuǎn)換成file對象
// 將base64轉(zhuǎn)換成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.復(fù)制文本
//復(fù)制文本
copyText(data){
let url = data;//需要復(fù)制的文本
//新建一個文本框
let oInput = document.createElement('input');
//賦值給文本框
oInput.value = url;
document.body.appendChild(oInput);
// 選擇對象;
oInput.select();
// 執(zhí)行瀏覽器復(fù)制命令
document.execCommand("Copy");
//復(fù)制完成刪除掉輸入框
oInput.remove()
console.log('復(fù)制成功')
}
29.數(shù)組對象去重
//uniqueByKey函數(shù)接受一個數(shù)組arr和一個用于比較的鍵key狸吞。函數(shù)內(nèi)部創(chuàng)建了一個空對象found,用來存儲已經(jīng)遇到的鍵值指煎。通過filter遍歷數(shù)組蹋偏,如果某個項的鍵值在found對象中已存在,則該項被過濾掉至壤;否則威始,該項被保留,并將鍵值添加到found對象中像街。這樣黎棠,就可以保證數(shù)組中每個項的指定鍵值都是唯一的晋渺。
uniqueByKey(arr, key) {
const found = {};
return arr.filter((item) => {
const keyValue = item[key];
if (found[keyValue]) {
// 如果在found對象中找到了keyValue,則不保留當(dāng)前項
return false;
} else {
// 否則保留當(dāng)前項葫掉,并在found對象中記錄下keyValue
found[keyValue] = true;
return true;
}
});
},