今日分享一篇積累和收集了很久的JS utils工具函式,文章程式碼量較多,建議收藏起來慢慢看,當哪一天需要用到的時候,開啟你塵封已久的收藏夾,相信能讓你的業務程式碼開發事半功倍。
彙集了時間相關,DOM相關,URL相關,判斷相關,圖片相關,快取相關等。部分邏輯處理較為簡單,如果是業務量較為複雜的情況建議要斟酌使用,但對於大部分的專案應該是綽綽有餘。接下來就進入程式碼部分吧~
時間相關
時間戳轉自定義格式時間
export const dateRegExp = (time, strText) => {
const date = new Date(time)
if (/(y+)/.test(strText)) {
strText = strText.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
}
const dataType = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds()
}
for (const typeKey in dataType) {
if (new RegExp(`(${typeKey})`).test(strText)) {
const typeValue = dataType[typeKey] + ''
strText = strText.replace(RegExp.$1, (RegExp.$1.length === 1 ? typeValue : padLeftZero(typeValue)))
}
}
return strText
}
格式化距離現在已過去的時間
export function formatPassTime(startTime) {
var currentTime = Date.parse(new Date()),
time = currentTime - startTime,
day = parseInt(time / (1000 * 60 * 60 * 24)),
hour = parseInt(time / (1000 * 60 * 60)),
min = parseInt(time / (1000 * 60)),
month = parseInt(day / 30),
year = parseInt(month / 12);
if (year) return year + "年前"
if (month) return month + "個月前"
if (day) return day + "天前"
if (hour) return hour + "小時前"
if (min) return min + "分鐘前"
else return '剛剛'
}
判斷兩個不同格式的日期是否為同一天
export function isSameDay(d1, d2) {
if (!d2) {
d2 = new Date();
}
var d1_year = d1.getFullYear(),
d1_month = d1.getMonth() + 1,
d1_date = d1.getDate();
var d2_year = d2.getFullYear(),
d2_month = d2.getMonth() + 1,
d2_date = d2.getDate()
return d1_date === d2_date && d1_month === d2_month && d1_year === d2_year;
}
判斷時間是不是今天
export function isTodayDate(time) {
if (new Date(time).toDateString() === new Date().toDateString()) {
return true;
}
return false;
}
URL 相關
URL 引數轉物件
export function parseQueryString(url) {
url = url ? url:window.location.search ;
let search = url[0] === '?' ? url : url.substring(url.lastIndexOf('?'));
let q = {};
search.replace(/([^?&=]+)=([^&]+)/g, (_, k, v) => q[k] = decodeURIComponent(v));
return q;
}
獲取URL引數
export function getQueryString(name) {
const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
const r = window.location.search.substr(1).match(reg)
if (r !== null) {
return decodeURI(r[2])
}
return null
}
獲取URL hash後面的引數
export getHashQueryString = (key) => {
const after = window.location.href.split('?')[1]
if (after) {
const reg = new RegExp(`(^|&)${ key }=([^&]*)(&|$)`)
const r = after.match(reg)
if (r != null) {
return decodeURIComponent(r[2])
}
return null
}
return null
}
物件序列化
export function serialize(query, encode = false) {
return Object.keys(query)
.map((key) => `${key}=${encode ? encodeURIComponent(query[key]) : query[key]}`)
.join('&')
}
判斷相關
判斷是否支援 Intersection
export function isSupportIntersection() {
return (
'IntersectionObserver' in window &&
'IntersectionObserverEntry' in window &&
'intersectionRatio' in window.IntersectionObserverEntry.prototype
)
}
判斷是否IOS
export const isIOS = (() => {
return /ios|iphone|ipad|ipod/.test(navigator.userAgent.toLowerCase())
})()
判斷是否安卓
export const isAndroid = (() {
return /android/.test(navigator.userAgent.toLowerCase())
})()
判斷微信內建瀏覽器
export function isWeixin() {
var ua = navigator.userAgent.toLowerCase();
return (ua.match(/MicroMessenger/i) == "micromessenger")
}
判斷是否支援webp格式 2種方式
export function checkSupportWebp() {
return (
document
.createElement('canvas')
.toDataURL('image/webp')
.indexOf('data:image/webp') === 0
)
}
export function checkSupportWebp2() {
var img = new Image();
img.onload = img.onerror = (event) => {
return event && event.type === "load" ? img.width == 1 : false;
};
img.src = "data:image/webp;base64,UklGRiQAAABXRUJQVlA4IBgAAAAwAQCdASoBAAEAAwA0JaQAA3AA/vuUAAA=";
}
判斷瀏覽器是否是移動端
export function isMobile() {
const agent = navigator.userAgent;
const k = ["android", "iphone", "ipod", "ipad", "windows phone", "mqqbrowser"];
let flag = false;
// Windows
if (agent.indexOf("Windows NT") < 0 || (agent.indexOf("Windows NT") >= 0 && agent.indexOf("compatible; MSIE 9.0;") >= 0)) {
// Mac PC
if (agent.indexOf("Windows NT") < 0 && agent.indexOf("Macintosh") < 0) {
for (let item of k) {
if (agent.indexOf(item) >= 0) {
flag = true;
break;
}
}
}
}
return flag;
}
檔案型別判斷
export function checkFileName(fileName, list) {
if (typeof fileName !== 'string') return;
let name = fileName.toLowerCase();
return list.some(i => name.endsWith(`.${i}`) === true)
}
export function isImage(fileName) {
return checkFileName(fileName, ['png', 'jpeg', 'jpg', 'png', 'bmp'])
}
export function isH5Video(fileName) {
return checkFileName(fileName, ['mp4', 'webm', 'ogg'])
}
export function isPdf(fileName) {
return checkFileName(fileName, ['pdf'])
}
export function isWord(fileName) {
return checkFileName(fileName, ['doc', 'docx'])
}
export function isExcel(fileName) {
return checkFileName(fileName, ['xlsx', 'xls'])
}
資料型別判斷
export function is(subject, type) {
return Object.prototype.toString.call(subject).substr(8, type.length).toLowerCase() === type
}
export function isArray(subject) {
return Array.isArray(subject)
}
export function isObject(subject) {
return is(subject, 'object')
}
...
export function isNum(subject) {
return !isNaN(subject) && is(subject, 'number')
}
DOM 相關
查詢元素是否存在某個 class
export function hasClass(el, className) {
let reg = new RegExp('(^|\\s)' + className + '(\\s|$)');
return reg.test(el.className);
}
給某個元素新增 class
export function addClass(el, className) {
if (hasClass(el, className)) {
return;
}
let curClass = el.className.split(' ');
curClass.push(className);
el.className = curClass.join(' ');
}
刪除某個元素的 class
export function removeClass(el, className) {
if (!hasClass(el, className)) {
return;
}
let reg = new RegExp('(^|\\s)' + className + '(\\s|$)', 'g');
el.className = el.className.replace(reg, ' ');
}
獲取頁面滾動距離
export function getScrollTop() {
let e = 0
return (
document.documentElement && document.documentElement.scrollTop
? (e = document.documentElement.scrollTop)
: document.body && (e = document.body.scrollTop),
e
)
}
滾動到某個位置回撥
export function distanceScroll(distance, callback) {
const scrollTop = document.body.scrollTop || document.documentElement.scrollTop
const docHeight = document.body.clientHeight
const screenHeight = window.screen.availHeight
const differ = scrollTop > docHeight - screenHeight - distance
if (differ) {
callback && callback()
}
}
撥打電話
export const callPhone = (phone) => {
const aElement = document.createElement('a')
aElement.setAttribute('href', `tel:${phone}`)
document.body.appendChild(aElement)
aElement.click()
document.body.removeChild(aElement)
}
複製文字
export function copy(value, callback) {
if (!document.queryCommandSupported('copy')) {
callback('暫不支援複製')
return
}
const textarea = document.createElement('textarea')
textarea.value = value
textarea.readOnly = Boolean('readOnly')
document.body.appendChild(textarea)
textarea.select()
textarea.setSelectionRange(0, value.length)
document.execCommand('copy')
textarea.remove()
callback('複製成功')
}
動態載入第三方js
export function asyncLoadScript(url) {
return new Promise(function (resolve, reject) {
const tag = document.getElementsByTagName('script')
for (const i of tag) {
if (i.src === url) {
resolve()
return
}
}
const script = document.createElement('script')
script.type = 'text/javascript'
script.src = url
script.onerror = reject
document.body.appendChild(script)
script.onload = () => {
resolve()
}
})
}
解決 requestAnimationFrame 的相容問題
export function requestAnimationFrame() {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || function (callback) {
return setTimeout(callback, (callback.interval || (100 / 60) / 2);
};
}()
動態建立form表單匯出資料(POST)
const postExport = (url, data = {}) => {
const form = document.createElement("form");
form.style.display = "none";
form.action = `${Config.baseURL}${url}`;
form.method = "post";
document.body.appendChild(form);
// 動態建立input並給value賦值
for (const key in data) {
const input = document.createElement("input");
input.type = "hidden";
input.name = key;
input.value = data[key];
form.appendChild(input);
}
form.submit();
form.remove();
}
圖片相關
base64轉Buffer
export function dataURItoBuffer(dataURI) {
var byteString = atob(dataURI.split(',')[1]);
var buffer = new ArrayBuffer(byteString.length);
var view = new Uint8Array(buffer);
for (var i = 0; i < byteString.length; i++) {
view[i] = byteString.charCodeAt(i);
}
return buffer;
}
base64轉Blob
export function dataURItoBlob(dataURI) {
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
var buffer = dataURItoBuffer(dataURI);
return new Blob([buffer], {
type: mimeString
});
}
調整拍照圖片方向
export function orientationHelper(canvas, ctx, orientation) {
var w = canvas.width;
var h = canvas.height;
if (orientation > 4) {
canvas.width = h;
canvas.height = w;
}
switch (orientation) {
case 2:
ctx.translate(w, 0);
ctx.scale(-1, 1);
break;
case 3:
ctx.translate(w, h);
ctx.rotate(Math.PI);
break;
case 4:
ctx.translate(0, h);
ctx.scale(1, -1);
break;
case 5:
ctx.rotate(0.5 * Math.PI);
ctx.scale(1, -1);
break;
case 6:
ctx.rotate(0.5 * Math.PI);
ctx.translate(0, -h);
break;
case 7:
ctx.rotate(0.5 * Math.PI);
ctx.translate(w, -h);
ctx.scale(-1, 1);
break;
case 8:
ctx.rotate(-0.5 * Math.PI);
ctx.translate(-w, 0);
break;
}
}
快取相關
獲取指定 Cookie 值
export const getCookie = (k) => {
const res = RegExp('(^|; )' + encodeURIComponent(k) + '=([^;]*)').exec(document.cookie)
return res && res[2]
}
設定 Cookie 值
export function setCookie(name, value, expriesDays, encode = false) {
var Days = expriesDays || 10
var exp = new Date()
exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000)
const val = encode ? escape(value) : value
document.cookie = name + '=' + val + ';domain=zhuanzhuan.com;path=/;expires=' + exp.toUTCString()
}
簡易版 Storage 操作,sessionStorage 及 localStorage 類似
const prefix = '_XXX_'
export function getStorage(key) {
const content = sessionStorage.getItem(`${prefix}${key}`)
if (content) {
try {
const params = JSON.parse(content)
const expires = params.expires
// 未設定過期 及 未過期
if (!expires || (expires && Date.now() <= expires)) {
return params.data
}
} catch (e) {
console.log(e)
}
}
}
export function setStorage(key, data = {}, expires) {
try {
const params = { data }
if (expires) {
params.expires = expires
}
sessionStorage.setItem(`${prefix}${key}`, JSON.stringify(params))
} catch (e) {
console.log(e)
}
}
數字相關
數字四捨五入,保留n位小數
export function round(number, n) {
n = n ? parseInt(n) : 0
if (n <= 0) return Math.round(number)
number = Math.round(number * Math.pow(10, n)) / Math.pow(10, n)
return number
}
數字每千位加逗號
export function toThousands(num) {
return num && num.toString()
.replace(/\d+/, function(s){
return s.replace(/(\d)(?=(\d{3})+$)/g, '$1,')
})
}
隨機數
export function random(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min)
}
字串相關
手機號碼中間4位隱藏星號
export function hideMobile(mobile) {
return mobile.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2")
}
檢測密碼強度 1:密碼弱 2:密碼中等 3:密碼強 4:密碼很強
export function checkPassWord(str) {
let level = 0;
if (str.length < 6) {
return level
};
if (/[0-9]/.test(str)) {
level++
};
if (/[a-z]/.test(str)) {
level++
};
if (/[A-Z]/.test(str)) {
level++
};
if(/\W/.test(str)){
level++
}
return level
}
隨機產生某個顏色
export function randomColor() {
return `rgb(${this.random(0, 255)}, ${this.random(0, 255)}, ${this.random(0, 255)})`
}
字串替換全部
export function replaceAll(s0, s1, s2){
return s0.replace(new RegExp(s1, "gm"), s2);
}
版本號比較
傳入兩個版本號,格式如:4.3.2,返回結果,小於-1,等於0,大於1。
export function compareVersion(v1, v2) {
var s1 = v1.split(".").map(v => parseInt(v));
var s2 = v2.split(".").map(v => parseInt(v));
var len1 = s1.length, len2 = s2.length, commonLen = Math.min(len1, len2);
for (var i = 0; i < commonLen; ++i) {
if (seq1[i] != seq2[i])
return seq1[i]<seq2[i] ? -1 : 1;
}
return len1 === len2 ? 0 : (len1 < len2 ? -1 : 1);
}
物件轉url字串供匯出介面(GET)使用
const objectToQueryString = (paramObj) => {
const tmpArray = []
// 特殊字元轉義
const filter = (str) => {
str += '' // 隱式轉換
str = str.replace(/%/g, '%25')
str = str.replace(/\+/g, '%2B')
str = str.replace(/ /g, '%20')
str = str.replace(/\//g, '%2F')
str = str.replace(/\?/g, '%3F')
str = str.replace(/&/g, '%26')
str = str.replace(/\=/g, '%3D')
str = str.replace(/#/g, '%23')
return str
}
for (const attr in paramObj) {
tmpArray.push(`${attr}=${filter(paramObj[attr])}`)
}
return tmpArray.join('&')
}
其他
函式防抖
export function debounce(fn, delay) {
delay = delay || 1000;
let timer = null;
return function () {
let context = this;
let arg = arguments;
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(context, arg);
}, delay);
};
}
節流函式
export function throttle(fn, delay = 300) {
let timer = null;
return function () {
let context = this;
let args = arguments;
if (!timer) {
timer = setTimeout(function () {
fn.apply(context, args);
clearTimeout(timer);
}, delay);
}
};
}
最後
除開本文所示的場景,也還有很多沒有列舉到的情況,如果你有認為很不錯的工具函式,歡迎留言交流~
專注前端開發,分享前端相關技術乾貨,公眾號:南城大前端(ID: nanchengfe)