日期格式化
function formatDate(date, fmt) {
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
}
let o = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds()
}
for (let k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
let str = o[k] + ''
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : ('00' + str).substr(str.length))
}
}
return fmt
}
去除空格
// type 0:去除全部空格止后,1:去除左邊空格,2:去除右邊空格
function cTrim (sInputString, type) {
var sTmpStr = ' ';
var i = -1;
if (type == 0 || type == 1) {
while (sTmpStr == ' ') {
++i;
sTmpStr = sInputString.substr(i, 1);
}
sInputString = sInputString.substring(i);
}
if (type == 0 || type == 2) {
sTmpStr = ' ';
i = sInputString.length;
while (sTmpStr == ' ') {
--i;
sTmpStr = sInputString.substr(i, 1);
}
sInputString = sInputString.substring(0, i + 1);
}
return sInputString;
}
url中取參數(shù)
function getQueryString(name) {
if (undefined == window.location) return null
var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
var r = window.location.search.substr(1).match(reg)
if (r != null) {
return unescape(r[2].replace(/\%20/g, '+'))
} else {
return null
}
}
獲取葛虐、設(shè)置胎源、刪除cookie值
// 獲取cookie第一種方法
function getCookie(e) {
var i = document.cookie.match(new RegExp('(^| )' + e + '=([^;]*)(;|$)'))
if (i !== null) {
return i[2]
} else {
return ''
}
}
// 獲取cookie第二種方法
function getCookie(name = '') {
if (document.cookie.length > 0) {
let start = document.cookie.indexOf(name + '=')
if (start !== -1) {
start = start + name.length + 1
let end = document.cookie.indexOf(';', start)
if (end === -1) end = document.cookie.length
return unescape(document.cookie.substring(start, end))
}
}
return null
}
// 設(shè)置cookie
function setCookie(name, value, expireHours) {
let exDate = new Date()
exDate.setTime(exDate.getTime() + expireHours * 60 * 60 * 1000)
document.cookie = name + '=' + escape(value) + (typeof expireHours === 'undefined' ? '' : ';expires=' + exDate.toGMTString())
}
// 刪除cookie
function delCookie(name = '') {
let exDate = new Date()
exDate.setTime(exDate.getTime() - 1)
let value = getCookie(name)
if (value !== null) {
document.cookie = name + '=' + escape(value) + ';expires=' + exDate.toGMTString()
}
}
設(shè)置、獲取挡闰、刪除乒融、清除sessionStorage(localStorage也是同樣操作)
function setSessionStorage(key, value) {
sessionStorage.setItem(key, value)
}
function getSessionStorage(key) {
return sessionStorage.getItem(key)
}
function delSessionStorage(key) {
sessionStorage.removeItem(key)
}
function clearSessionStorage() {
sessionStorage.clear()
}
獲取設(shè)備號(hào)掰盘,安卓,ios赞季,web
function getDeviceType() {
var deviceType = 'WEB' //其他
var u = navigator.userAgent
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
if (isAndroid) {
deviceType = 'ANDROID'
} else if (isiOS) {
deviceType = 'IOS'
}
return deviceType
}
正則檢測(cè)愧捕,手機(jī)號(hào)、姓名申钩、郵箱次绘、身份證
let RegExp = {
// 檢測(cè)手機(jī)號(hào)
checkMobile(s) {
var regu = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
if (regu.test(s)) {
return true
} else {
return false
}
},
// 檢測(cè)姓名 必須要有兩個(gè)漢字
checkNomalName(s) {
var regu = /^[\u4e00-\u9fa5]{2,}$/;
if (regu.test(s)) {
return true;
} else {
return false;
}
},
// 檢測(cè)郵箱
isEmail(str) {
var myReg = /^[-_A-Za-z0-9]+@([_A-Za-z0-9]+\.)+[A-Za-z0-9]{2,3}$/;
if (myReg.test(str)) return true;
return false;
},
// 檢測(cè)身份證
checkIdCard(idCard) {
var regIdCard = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/
//如果通過該驗(yàn)證,說明身份證格式正確撒遣,但準(zhǔn)確性還需計(jì)算
if (regIdCard.test(idCard)) {
if (idCard.length == 18) {
var idCardWi = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2) //將前17位加權(quán)因子保存在數(shù)組里
var idCardY = new Array(1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2) //這是除以11后邮偎,可能產(chǎn)生的11位余數(shù)、驗(yàn)證碼义黎,也保存成數(shù)組
var idCardWiSum = 0 //用來保存前17位各自乖以加權(quán)因子后的總和
for (var i = 0; i < 17; i++) {
idCardWiSum += idCard.substring(i, i + 1) * idCardWi[i]
}
var idCardMod = idCardWiSum % 11 //計(jì)算出校驗(yàn)碼所在數(shù)組的位置
var idCardLast = idCard.substring(17) //得到最后一位身份證號(hào)碼
//如果等于2禾进,則說明校驗(yàn)碼是10,身份證號(hào)碼最后一位應(yīng)該是X
if (idCardMod == 2) {
if (idCardLast == 'X' || idCardLast == 'x') {
return true
} else {
return false
}
} else {
//用計(jì)算出的驗(yàn)證碼與最后一位身份證號(hào)碼匹配廉涕,如果一致泻云,說明通過,否則是無效的身份證號(hào)碼
if (idCardLast == idCardY[idCardMod]) {
return true
} else {
return false
}
}
}
} else {
return false
}
}
}
身份證打馬
function idCardMask (idCard = '') {
return idCard.substr(0, 1) + idCard.slice(1, -4).replace(/\d/g, '*') + idCard.substr(-4)
}
微信環(huán)境狐蜕、小程序環(huán)境檢測(cè)
// 微信環(huán)境
function isWeiXinWeb () {
return navigator.userAgent.toLowerCase().indexOf('micromessenger') != -1
}
// 小程序環(huán)境
function isWechatApplet() {
const ua = window.navigator.userAgent.toLowerCase()
return new Promise(resolve => {
if (ua.indexOf('micromessenger') == -1) {
//不在微信或者小程序中
resolve(false)
} else {
wx.miniProgram.getEnv(res => {
if (res.miniprogram) {
//在小程序中
resolve(true)
} else {
resolve(false)
}
})
}
})
}
// 使用說明
let isWx = isWeiXinWeb
let isWechatApp = false
isWechatApplet().then(res => {
isWechatApp = res
}).catch(res => {
isWechatApp = false
})
數(shù)組方法
// 數(shù)組最大值
function arrayMax(arr) {
return Math.max.apply(null, arr)
}
// 數(shù)組最小值
function arrayMin(arr) {
return Math.min.apply(null, arr)
}
// 數(shù)組并集
function arrayUnion(arr1, arr2) {
return [...new Set([...arr1, ...arr2])]
}
// 數(shù)組交集
function arrayIntersect(arr1, arr2) {
// let arr3 = [...arr1].filter(value => arr2.includes(value))
// return [...new Set([...arr3])]
return [...new Set([...arr1].filter(value => arr2.includes(value)))]
}
// 數(shù)組差集
function arrayDiff(arr1, arr2) {
return [...new Set([...arr1].filter(value => !arr2.includes(value)))]
}
// 數(shù)組去重
function arrayUnique(arr) {
return [...new Set([...arr])]
}
localStorage存儲(chǔ)宠纯,并且設(shè)定過期時(shí)間
let handleLocalStorage = {
// 存儲(chǔ)localStorage,并且設(shè)定過期時(shí)間
setLocalStorageItem(key, value, exp) {
var obj = new Object(),
expires = exp.expires || null
obj.value = value
obj.time = new Date().getTime()
// expires 類型
if (expires === null) {
delete obj.expires
} else if (typeof expires === 'object') {
obj.expires = expires.getTime() - obj.time
} else if (typeof expires === 'number') {
if ((expires | 0) !== expires) {
throw new Error('expires must be integer number!')
}
// expires 小于 365层释、366 則婆瓜,按天算。否則按時(shí)間戳算
let days = new Date().getFullYear() % 4 === 0 ? 366 : 365
if (expires <= days && expires > 0) {
obj.expires = expires * 1000 * 60 * 60 * 24
} else if (expires > days) {
obj.expires = expires
} else if (expires <= 0) {
this.removeLocalStorageItem(key)
}
}
localStorage.setItem(key, JSON.stringify(obj))
},
// getLocalStorageItem
getLocalStorageItem(key) {
var obj = JSON.parse(localStorage.getItem(key))
if (obj === 'null' || obj === null) return null
var expires = obj.expires,
now = new Date().getTime(),
time = obj.time
if (now - time >= expires || now < time) {
localStorage.removeItem(key)
return null
} else {
return obj.value
}
},
// removeLocalStorageItem
removeLocalStorageItem(key) {
if (this.getLocalStorageItem(key) !== null) {
localStorage.removeItem(key)
return this.getLocalStorageItem(key) === null ? true : false
}
return true
},
}
// 使用贡羔,假定廉白,有一個(gè)緩存地址(address),需要緩存一天治力,一天之后蒙秒,自動(dòng)失效
let address = JSON.parse(handleLocalStorage. getLocalStorageItem('address'))
let limitTime = address.time + address.expires
let now = new Date().getTime()
// 已經(jīng)過期, 重新定位
if (limitTime <= now) {
handleLocalStorage.removeLocalStorageItem('address')
}
if(localStorage.address) {
// 緩存未過期宵统,直接取localStorage中的地址
} else {
// 緩存過期晕讲,重新定位
// 定位結(jié)束,需要將定位到的信息重新存入localStorage中
handleLocalStorage.setLocalStorageItem('address', '新地址' , {expires: 1})
}
js操作頁面马澈,滾動(dòng)到具體位置
// 簡(jiǎn)單的方法 參數(shù)一是時(shí)間瓢省,參數(shù)二是距離,但是有些機(jī)型痊班,并不能兼容這個(gè)方法
window.scrollTo(10, 200)
// 模擬滾動(dòng) 參數(shù)一是距離勤婚,參數(shù)二是時(shí)間
function scrollTop(number = 0, time) {
if (!time) {
document.body.scrollTop = document.documentElement.scrollTop = number
return number
}
const spacingTime = 20
let spacingInex = time / spacingTime
let nowTop = document.body.scrollTop + document.documentElement.scrollTop
let everTop = (number - nowTop) / spacingInex
let scrollTimer = setInterval(() => {
if (spacingInex > 0) {
spacingInex--
scrollTop((nowTop += everTop))
} else {
clearInterval(scrollTimer)
}
}, spacingTime)
}
// 使用,將頁面滾動(dòng)到某個(gè)元素
let ele = document.getElementById('scrollId')
this.scrollTop(ele.offsetTop, 200)