共计 11271 个字符,预计需要花费 29 分钟才能阅读完成。
今日分享一篇积攒和收集了很久的 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)
正文完