JavaScript常用的工具函數(shù)分享
前言;
JavaScript ( JS ) 是一種具有函數(shù)優(yōu)先的輕量級(jí),解釋型或即時(shí)編譯型的編程語言。雖然它是作為開發(fā)Web 頁面的腳本語言而出名的,但是它也被用到了很多非瀏覽器環(huán)境中等等。
格式化時(shí)間戳
export function formatDateTimeStamp(date, fmt) { ? ? // 格式化時(shí)間戳 : formatDateTimeStamp(new Date(time),'yyyy-MM-dd hh:mm:ss') ? ? 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 : ? ? ? ? ? ? ? ? padLeftZero(str)) ? ? ? ? } ? ? } ? ? return fmt } function padLeftZero(str) { ? ? return ('00' + str).substr(str.length); } export function parseTime(time, cFormat) { ? ? if (arguments.length === 0) { ? ? ? ? return null ? ? } ? ? const format = cFormat || '{y}-{m}-vvxyksv9kd {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(/{([ymdhisa])+}/g, (result, key) => { ? ? ? ? const value = formatObj[key] ? ? ? ? // Note: getDay() returns 0 on Sunday ? ? ? ? if (key === 'a') { ? ? ? ? ? ? return ['日', '一', '二', '三', '四', '五', '六'][value] ? ? ? ? } ? ? ? ? return value.toString().padStart(2, '0') ? ? }) ? ? return time_str }
時(shí)間格式化 幾分鐘前 幾小時(shí)前
export function formatTime(time, option) { ? ? if (('' + time).length === 10) { ? ? ? ? time = parseInt(time) * 1000 ? ? } else { ? ? ? ? time = +time ? ? } ? ? const d = new Date(time) ? ? const now = Date.now() ? ? const diff = (now - d) / 1000 ? ? if (diff < 30) { ? ? ? ? return '剛剛' ? ? } else if (diff < 3600) { ? ? ? ? // less 1 hour ? ? ? ? return Math.ceil(diff / 60) + '分鐘前' ? ? } else if (diff < 3600 * 24) { ? ? ? ? return Math.ceil(diff / 3600) + '小時(shí)前' ? ? } else if (diff < 3600 * 24 * 2) { ? ? ? ? return '1天前' ? ? } ? ? if (option) { ? ? ? ? return parseTime(time, option) ? ? } else { ? ? ? ? return ( ? ? ? ? ? ? d.getMonth() + ? ? ? ? ? ? 1 + ? ? ? ? ? ? '月' + ? ? ? ? ? ? d.getDate() + ? ? ? ? ? ? '日' + ? ? ? ? ? ? d.getHours() + ? ? ? ? ? ? '時(shí)' + ? ? ? ? ? ? d.getMinutes() + ? ? ? ? ? ? '分' ? ? ? ? ) ? ? } } function pluralize(time, label) { ? ? if (time === 1) { ? ? ? ? return time + label + ' ago' ? ? } ? ? return time + label + 's' + ' ago' } export function timeAgo(time) { ? ? const between = Date.now() / 1000 - Number(time) ? ? if (between < 3600) { ? ? ? ? return pluralize(~~(between / 60), ' minute') ? ? } else if (between < 86400) { ? ? ? ? return pluralize(~~(between / 3600), ' hour') ? ? } else { ? ? ? ? return pluralize(~~(between / 86400), ' day') ? ? } }
url參數(shù)轉(zhuǎn)為對象
export function getQueryObject(url) { ? ? url = url == null ? window.location.href : url ? ? const search = url.substring(url.lastIndexOf('?') + 1) ? ? const obj = {} ? ? const reg = /([^?&=]+)=([^?&=]*)/g ? ? search.replace(reg, (rs, $1, $2) => { ? ? ? ? const name = decodeURIComponent($1) ? ? ? ? let val = decodeURIComponent($2) ? ? ? ? val = String(val) ? ? ? ? obj[name] = val ? ? ? ? return rs ? ? }) ? ? return obj } export function param2Obj(url) { ? ? const search = url.split('?')[1] ? ? if (!search) { ? ? ? ? return {} ? ? } ? ? return JSON.parse( ? ? ? ? '{"' + ? ? ? ? decodeURIComponent(search) ? ? ? ? .replace(/"/g, '\\"') ? ? ? ? .replace(/&/g, '","') ? ? ? ? .replace(/=/g, '":"') ? ? ? ? .replace(/\+/g, ' ') + ? ? ? ? '"}' ? ? ) }
對象序列化【對象轉(zhuǎn)url參數(shù)】
function cleanArray(actual) { ? ? const newArray = [] ? ? for (let i = 0; i < actual.length; i++) { ? ? ? ? if (actual[i]) { ? ? ? ? ? ? newArray.push(actual[i]) ? ? ? ? } ? ? } ? ? return newArray } export function param(obj) { ? ? if (!obj) return '' ? ? return cleanArray( ? ? ? ? Object.keys(obj).map(key => { ? ? ? ? ? ? if (obj[key] === undefined) return '' ? ? ? ? ? ? return encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]) ? ? ? ? }) ? ? ).join('&') } export function stringfyQueryStr(obj) {? ? ? if (!obj) return ''; ? ? let pairs = []; ? ? for (let key in obj) { ? ? ? ? let value = obj[key]; ? ? ? ? if (value instanceof Array) { ? ? ? ? ? ? for (let i = 0; i < value.length; ++i) { ? ? ? ? ? ? ? ? pairs.push(encodeURIComponent(key + '[' + i + ']') + '=' + encodeURIComponent(value[i])); ? ? ? ? ? ? } ? ? ? ? ? ? continue;`在這里插入代碼片` ? ? ? ? } ? ? ? ? pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key])); ? ? } ? ? return pairs.join('&'); } param({name:'1111',sex:'wwww'}) stringfyQueryStr({name:'1111',sex:'wwww'})
本地存儲(chǔ)
export const store = { // 本地存儲(chǔ) ? ? set: function(name, value, day) { // 設(shè)置 ? ? ? ? let d = new Date() ? ? ? ? let time = 0 ? ? ? ? day = (typeof(day) === 'undefined' || !day) ? 1 : day // 時(shí)間,默認(rèn)存儲(chǔ)1天 ? ? ? ? time = d.setHours(d.getHours() + (24 * day)) // 毫秒 ? ? ? ? localStorage.setItem(name, JSON.stringify({ ? ? ? ? ? ? data: value, ? ? ? ? ? ? time: time ? ? ? ? }))? ? ? }, ? ? get: function(name) { // 獲取 ? ? ? ? let data = localStorage.getItem(name) ? ? ? ? if (!data) { ? ? ? ? ? ? return null ? ? ? ? } ? ? ? ? let obj = JSON.parse(data) ? ? ? ? if (new Date().getTime() > obj.time) { // 過期 ? ? ? ? ? ? localStorage.removeItem(name) ? ? ? ? ? ? return null ? ? ? ? } else { ? ? ? ? ? ? return obj.data ? ? ? ? } ? ? }, ? ? clear: function(name) { // 清空 ? ? ? ? if (name) { // 刪除鍵為name的緩存 ? ? ? ? ? ? localStorage.removeItem(name) ? ? ? ? } else { // 清空全部 ? ? ? ? ? ? localStorage.clear() ? ? ? ? } ? ? } }
cookie操作
export const cookie = { // cookie操作【set,get,del】 ? ? set: function(name, value, day) { ? ? ? ? let oDate = new Date() ? ? ? ? oDate.setDate(oDate.getDate() + (day || 30)) ? ? ? ? document.cookie = name + '=' + value + ';expires=' + oDate + "; path=/;" ? ? }, ? ? get: function(name) { ? ? ? ? let str = document.cookie ? ? ? ? let arr = str.split('; ') ? ? ? ? for (let i = 0; i < arr.length; i++) { ? ? ? ? ? ? let newArr = arr[i].split('=') ? ? ? ? ? ? if (newArr[0] === name) { ? ? ? ? ? ? ? ? return newArr[1] ? ? ? ? ? ? } ? ? ? ? } ? ? }, ? ? del: function(name) { ? ? ? ? this.set(name, '', -1) ? ? } }
數(shù)字格式化單位
export function numberFormatter(num, digits)? { ? ? const si = [{ ? ? ? ? ? ? value: 1E18, ? ? ? ? ? ? symbol: 'E' ? ? ? ? }, ? ? ? ? { ? ? ? ? ? ? value: 1E15, ? ? ? ? ? ? symbol: 'P' ? ? ? ? }, ? ? ? ? { ? ? ? ? ? ? value: 1E12, ? ? ? ? ? ? symbol: 'T' ? ? ? ? }, ? ? ? ? { ? ? ? ? ? ? value: 1E9, ? ? ? ? ? ? symbol: 'G' ? ? ? ? }, ? ? ? ? { ? ? ? ? ? ? value: 1E6, ? ? ? ? ? ? symbol: 'M' ? ? ? ? }, ? ? ? ? { ? ? ? ? ? ? value: 1E3, ? ? ? ? ? ? symbol: 'k' ? ? ? ? } ? ? ] ? ? for (let i = 0; i < si.length; i++) { ? ? ? ? if (num >= si[i].value) { ? ? ? ? ? ? return (num / si[i].value).toFixed(digits).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, '$1') + si[i].symbol ? ? ? ? } ? ? } ? ? return num.toString() }
數(shù)字千位過濾
export function toThousandFilter(num) { ? ? let targetNum = (num || 0).toString() ? ? if (targetNum.includes('.')) { ? ? ? ? let arr = num.split('.') ? ? ? ? return arr[0].replace(/^-?\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ',')) + '.' + arr[1] ? ? } else { ? ? ? ? return targetNum.replace(/^-?\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ',')) ? ? } }
過濾成版本號(hào)
export function versionFilter(versions) { ? ? let v0 = (versions & 0xff000000) >> 24 ? ? let v1 = (versions & 0xff0000) >> 16 ? ? let v2 = (versions & 0xff00) >> 8 ? ? let v3 = versions & 0xff ? ? return `${v0}.${v1}.${v2}.${v3}` }
首字母大寫
export function uppercaseFirst(string) { ? ? return string.charAt(0).toUpperCase() + string.slice(1) }
class 操作
export function hasClass(ele, cls) { ? ? return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)')) } export function addClass(ele, cls) { ? ? if (!hasClass(ele, cls)) ele.className += ' ' + cls } export function removeClass(ele, cls) { ? ? if (hasClass(ele, cls)) { ? ? ? ? const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)') ? ? ? ? ele.className = ele.className.replace(reg, ' ') ? ? } }
文本復(fù)制功能
const copyTxt = function(text, fn) { // 復(fù)制功能 ? ? if (typeof document.execCommand !== 'function') { ? ? ? ? console.log('復(fù)制失敗,請長按復(fù)制') ? ? ? ? return ? ? } ? ? var dom = document.createElement('textarea') ? ? dom.value = text ? ? dom.setAttribute('style', 'display: block;width: 1px;height: 1px;') ? ? document.body.appendChild(dom) ? ? dom.select() ? ? var result = document.execCommand('copy') ? ? document.body.removeChild(dom) ? ? if (result) { ? ? ? ? console.log('復(fù)制成功') ? ? ? ? typeof fn === 'function' && fn() ? ? ? ? return ? ? } ? ? if (typeof document.createRange !== 'function') { ? ? ? ? console.log('復(fù)制失敗,請長按復(fù)制') ? ? ? ? return ? ? } ? ? var range = document.createRange() ? ? var div = document.createElement('div') ? ? div.innerhtml = text ? ? div.setAttribute('style', 'height: 1px;fontSize: 1px;overflow: hidden;') ? ? document.body.appendChild(div) ? ? range.selectNode(div) ? ? var selection = window.getSelection() ? ? console.log(selection) ? ? if (selection.rangeCount > 0) { ? ? ? ? selection.removeAllRanges() ? ? } ? ? selection.addRange(range) ? ? document.execCommand('copy') ? ? typeof fn === 'function' && fn() ? ? console.log('復(fù)制成功') }
判斷是否是一個(gè)數(shù)組
export const castArray = value => (Array.isArray(value) ? value : [value]) export const castArray = arr=> ?Object.prototype.toString.call(arr) === '[object Array]'
判斷是否是一個(gè)空數(shù)組
export const isEmpty = (arr) => !Array.isArray(arr) || arr.length === 0
克隆一個(gè)數(shù)組
/** ?* @param {Array} arr? ?*/ const clone = (arr) => arr.slice(0); // Or const clone = (arr) => [...arr]; // Or const clone = (arr) => Array.from(arr); // Or const clone = (arr) => arr.map((x) => x); // Or const clone = (arr) => JSON.parse(JSON.stringify(arr)); // Or const clone = (arr) => arr.concat([]);
數(shù)組去重
/** ?* @param {Array} arr ?* @returns {Array} ?*/ export const uniqueArray = (arr) => Array.from(new Set(arr))? // Or export const uniqueArray = (arr) => arr.filter((el, i, array) => array.indexOf(el) === i) // Or export const uniqueArray = (arr) => arr.reduce((acc, el) => (acc.includes(el) ? acc : [...acc, el]), [])
是否為PC端
export const isPC = function() { // 是否為PC端 ? ? let userAgentInfo = navigator.userAgent ? ? let Agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod'] ? ? let flag = true ? ? for (let v = 0; v < Agents.length; v++) { ? ? ? ? if (userAgentInfo.indexOf(Agents[v]) > 0) { ? ? ? ? ? ? flag = false ? ? ? ? ? ? break ? ? ? ? } ? ? } ? ? return flag }
判斷是否為微信
export const isWx = () => { // 判斷是否為微信 ? ? var ua = window.navigator.userAgent.toLowerCase() ? ? if (ua.match(/MicroMessenger/i) === 'micromessenger') { ? ? ? ? return true ? ? } ? ? return false }
設(shè)備判斷:android、ios、web
export const isDevice = function() { // 判斷是android還是ios還是web ? ? var ua = navigator.userAgent.toLowerCase() ? ? if (ua.match(/iPhone\sOS/i) === 'iphone os' || ua.match(/iPad/i) === 'ipad') { // ios ? ? ? ? return 'iOS' ? ? } ? ? if (ua.match(/Android/i) === 'android') { ? ? ? ? return 'Android' ? ? } ? ? return 'Web' }
常見正則校驗(yàn)
/*正則匹配*/ export const normalReg = (str, type) => { ? ? switch (type) { ? ? ? ? case 'phone': ? //手機(jī)號(hào)碼 ? ? ? ? ? ? return /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(str); ? ? ? ? case 'tel': ? ? //座機(jī) ? ? ? ? ? ? return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str); ? ? ? ? case 'card': ? ?//身份證 ? ? ? ? ? ? return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str); ? ? ? ? case 'pwd': ? ? //密碼以字母開頭,長度在6~18之間,只能包含字母、數(shù)字和下劃線 ? ? ? ? ? ? return /^[a-zA-Z]\w{5,17}$/.test(str) ? ? ? ? case 'postal': ?//郵政編碼 ? ? ? ? ? ? return /[1-9]\d{5}(?!\d)/.test(str); ? ? ? ? case 'QQ': ? ? ?//QQ號(hào) ? ? ? ? ? ? return /^[1-9][0-9]{4,9}$/.test(str); ? ? ? ? case 'email': ? //郵箱 ? ? ? ? ? ? return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str); ? ? ? ? case 'money': ? //金額(小數(shù)點(diǎn)2位) ? ? ? ? ? ? return /^\d*(?:\.\d{0,2})?$/.test(str); ? ? ? ? case 'URL': ? ? //網(wǎng)址 ? ? ? ? ? ? return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(str) ? ? ? ? case 'IP': ? ? ?//IP ? ? ? ? ? ? return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(str); ? ? ? ? case 'date': ? ?//日期時(shí)間 ? ? ? ? ? ? return /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(str) || /^(\d{4})\-(\d{2})\-(\d{2})$/.test(str) ? ? ? ? case 'number': ?//數(shù)字 ? ? ? ? ? ? return /^[0-9]$/.test(str); ? ? ? ? case 'positiveInteger': ?//正整數(shù) ? ? ? ? ? ? return /^[1-9]\d*$/.test(str); ? ? ? ? case 'price': ?//價(jià)格 ? ? ? ? ? ? return /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(str);//價(jià)格非0則去掉'?' ? ? ? ? case 'english': //英文 ? ? ? ? ? ? return /^[a-zA-Z]+$/.test(str); ? ? ? ? case 'chinese': //中文 ? ? ? ? ? ? return /^[\u4E00-\u9FA5]+$/.test(str); ? ? ? ? case 'lower': ? //小寫 ? ? ? ? ? ? return /^[a-z]+$/.test(str); ? ? ? ? case 'upper': ? //大寫 ? ? ? ? ? ? return /^[A-Z]+$/.test(str); ? ? ? ? case 'HTML': ? ?//HTML標(biāo)記 ? ? ? ? ? ? return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str); ? ? ? ? default: ? ? ? ? ? ? return true; ? ? } }
去除字符串空格
export const trim = function(str, type) {? ? ? type = type || 1 ? ? switch (type) { ? ? ? ? case 1: ? ? ? ? ? ? return str.replace(/\s+/g, '') ? ? ? ? case 2: ? ? ? ? ? ? return str.replace(/(^\s*)|(\s*$)/g, '') ? ? ? ? case 3: ? ? ? ? ? ? return str.replace(/(^\s*)/g, '') ? ? ? ? case 4: ? ? ? ? ? ? return str.replace(/(\s*$)/g, '') ? ? ? ? default: ? ? ? ? ? ? return str ? ? } }
過濾html代碼
export const filterTag = function(str) { // 過濾html代碼(把<>轉(zhuǎn)換) ? ? str = str.replace(/&/ig, '&') ? ? str = str.replace(/</ig, '<') ? ? str = str.replace(/>/ig, '>') ? ? str = str.replace(' ', ' ') ? ? return str }
生成隨機(jī)數(shù)范圍
export const random = function(min, max) { // 生成隨機(jī)數(shù)范圍 ? ? if (arguments.length === 2) { ? ? ? ? return Math.floor(min + Math.random() * ((max + 1) - min)) ? ? } else { ? ? ? ? return null ? ? } }
判斷圖片加載完成
export const imgLoadAll = function(arr, callback) { // 圖片加載 ? ? let arrImg = [] ? ? for (let i = 0; i < arr.length; i++) { ? ? ? ? let img = new Image() ? ? ? ? img.src = arr[i] ? ? ? ? img.onload = function() { ? ? ? ? ? ? arrImg.push(this) ? ? ? ? ? ? if (arrImg.length == arr.length) { ? ? ? ? ? ? ? ? callback && callback() ? ? ? ? ? ? } ? ? ? ? } ? ? } }
光標(biāo)所在位置插入字符
export const insertAtCursor = function(dom, val) { // 光標(biāo)所在位置插入字符 ? ? if (document.selection) { ? ? ? ? dom.focus() ? ? ? ? let sel = document.selection.createRange() ? ? ? ? sel.text = val ? ? ? ? sel.select() ? ? } else if (dom.selectionStart || dom.selectionStart == '0') { ? ? ? ? let startPos = dom.selectionStart ? ? ? ? let endPos = dom.selectionEnd ? ? ? ? let restoreTop = dom.scrollTop ? ? ? ? dom.value = dom.value.substring(0, startPos) + val + dom.value.substring(endPos, dom.value.length) ? ? ? ? if (restoreTop > 0) { ? ? ? ? ? ? dom.scrollTop = restoreTop ? ? ? ? } ? ? ? ? dom.focus() ? ? ? ? dom.selectionStart = startPos + val.length ? ? ? ? dom.selectionEnd = startPos + val.length ? ? } else { ? ? ? ? dom.value += val ? ? ? ? dom.focus() ? ? } }
圖片地址轉(zhuǎn)base64
?export const getBase64 = function(img) {? ? ? //傳入圖片路徑,返回base64,使用getBase64(url).then(function(base64){},function(err){});? ? ? let getBase64Image = function(img, width, height) {? ? ? //width、height調(diào)用時(shí)傳入具體像素值,控制大小,不傳則默認(rèn)圖像大小 ? ? ? ? let canvas = document.createElement("canvas"); ? ? ? ? canvas.width = width ? width : img.width; ? ? ? ? canvas.height = height ? height : img.height; ? ? ? ? let ctx = canvas.getContext("2d"); ? ? ? ? ctx.drawImage(img, 0, 0, canvas.width, canvas.height); ? ? ? ? let dataURL = canvas.toDataURL(); ? ? ? ? return dataURL; ? ? } ? ? let image = new Image(); ? ? image.crossOrigin = ''; ? ? image.src = img; ? ? let deferred = $.Deferred(); ? ? if (img) { ? ? ? ? image.onload = function() { ? ? ? ? ? ? deferred.resolve(getBase64Image(image)); ? ? ? ? } ? ? ? ? return deferred.promise(); ? ? } }
base64圖片下載功能
export const downloadFile ?= (base64, fileName) => { ? ? let base64ToBlob = (code) => { ? ? ? ? let parts = code.split(';base64,'); ? ? ? ? let contentType = parts[0].split(':')[1]; ? ? ? ? let raw = window.atob(parts[1]); ? ? ? ? let rawLength = raw.length; ? ? ? ? let uInt8Array = new Uint8Array(rawLength); ? ? ? ? for (let i = 0; i < rawLength; ++i) { ? ? ? ? ? ? uInt8Array[i] = raw.charCodeAt(i); ? ? ? ? } ? ? ? ? return new Blob([uInt8Array], { ? ? ? ? ? ? type: contentType ? ? ? ? }); ? ? }; ? ? let aLink = document.createElement('a'); ? ? let blob = base64ToBlob(base64); //new Blob([content]); ? ? let evt = document.createEvent("HTMLEvents"); ? ? evt.initEvent("click", true, true);? ? ? //initEvent不加后兩個(gè)參數(shù)在FF下會(huì)報(bào)錯(cuò) ?事件類型,是否冒泡,是否阻止瀏覽器的默認(rèn)行為 ? ? aLink.download = fileName; ? ? aLink.href = URL.createObjectURL(blob); ? ? aLink.click(); }
瀏覽器是否支持webP格式圖片
export const webPBool = () => !![].map &&? document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') == 0
H5軟鍵盤縮回、彈起回調(diào)
/* 當(dāng)軟件鍵盤彈起會(huì)改變當(dāng)前 window.innerHeight 監(jiān)聽這個(gè)值變化 [downCb 當(dāng)軟鍵盤彈起后,縮回的回調(diào),upCb 當(dāng)軟鍵盤彈起的回調(diào)] */ export function(downCb, upCb) {? ? ? var clientHeight = window.innerHeight ? ? downCb = typeof downCb === 'function' ? downCb : function() {} ? ? upCb = typeof upCb === 'function' ? upCb : function() {} ? ? window.addEventListener('resize', () => { ? ? ? ? var height = window.innerHeight ? ? ? ? if (height === clientHeight) { ? ? ? ? ? ? downCb() ? ? ? ? } ? ? ? ? if (height < clientHeight) { ? ? ? ? ? ? upCb() ? ? ? ? } ? ? }) }
對象屬性剔除
function omit(object, props=[]){ ? ? ? let res = {} ? ? ? Object.keys(object).forEach(key=>{ ? ? ? ? ? ? if(props.includes(key) === false){ ? ? ? ? ? ? ? ? ? res[key] = typeof object[key] === 'object' && object[key] !== null ? jsON.parse(jsON.stringify(object[key])) : object[key] ? ? ? ? ? ? } ? ? ? }) ? ? ? ?? ? ? return res } // for example let data = { ?id: 1, ?title: '12345', ?name: '男'} omit(data, ['id'])? // data ---> {title: 'xxx', name: '男'}
深拷貝
export function deepClone(source) { ? ? if (!source && typeof source !== 'object') { ? ? ? ? throw new Error('error arguments', 'deepClone') ? ? } ? ? const targetObj = source.constructor === Array ? [] : {} ? ? Object.keys(source).forEach(keys => { ? ? ? ? if (source[keys] && typeof source[keys] === 'object') { ? ? ? ? ? ? targetObj[keys] = deepClone(source[keys]) ? ? ? ? } else { ? ? ? ? ? ? targetObj[keys] = source[keys] ? ? ? ? } ? ? }) ? ? return targetObj }
函數(shù)防抖
export function debounce(func, wait, immediate) { ? ? let timeout, args, context, timestamp, result ? ? const later = function() { ? ? ? ? // 據(jù)上一次觸發(fā)時(shí)間間隔 ? ? ? ? const last = +new Date() - timestamp ? ? ? ? // 上次被包裝函數(shù)被調(diào)用時(shí)間間隔 last 小于設(shè)定時(shí)間間隔 wait ? ? ? ? if (last < wait && last > 0) { ? ? ? ? ? ? timeout = setTimeout(later, wait - last) ? ? ? ? } else { ? ? ? ? ? ? timeout = null ? ? ? ? ? ? // 如果設(shè)定為immediate===true,因?yàn)殚_始邊界已經(jīng)調(diào)用過了此處無需調(diào)用 ? ? ? ? ? ? if (!immediate) { ? ? ? ? ? ? ? ? result = func.apply(context, args) ? ? ? ? ? ? ? ? if (!timeout) context = args = null ? ? ? ? ? ? } ? ? ? ? } ? ? } ? ? return function(...args) { ? ? ? ? context = this ? ? ? ? timestamp = +new Date() ? ? ? ? const callNow = immediate && !timeout ? ? ? ? // 如果延時(shí)不存在,重新設(shè)定延時(shí) ? ? ? ? if (!timeout) timeout = setTimeout(later, wait) ? ? ? ? if (callNow) { ? ? ? ? ? ? result = func.apply(context, args) ? ? ? ? ? ? context = args = null ? ? ? ? } ? ? ? ? return result ? ? } }
函數(shù)節(jié)流
/** ?* @param {Function} func 目標(biāo)函數(shù) ?* @param {Number} wait ?延遲執(zhí)行毫秒數(shù) ?* @param {Number} type ?type 1 表時(shí)間戳版,2 表定時(shí)器版 ?*/ export function(func, wait ,type) {? ? ? if(type===1){ ? ? ? ? let previous = 0; ? ? }else if(type===2){ ? ? ? ? let timeout; ? ? } ? ? return function() { ? ? ? ? let context = this; ? ? ? ? let args = arguments; ? ? ? ? if(type===1){ ? ? ? ? ? ? let now = Date.now(); ? ? ? ? ? ? if (now - previous > wait) { ? ? ? ? ? ? ? ? func.apply(context, args); ? ? ? ? ? ? ? ? previous = now; ? ? ? ? ? ? } ? ? ? ? }else if(type===2){ ? ? ? ? ? ? if (!timeout) { ? ? ? ? ? ? ? ? timeout = setTimeout(() => { ? ? ? ? ? ? ? ? ? ? timeout = null; ? ? ? ? ? ? ? ? ? ? func.apply(context, args) ? ? ? ? ? ? ? ? }, wait) ? ? ? ? ? ? } ? ? ? ? } ? ? } }
到此這篇關(guān)于JavaScript常用的工具函數(shù)分享的文章就介紹到這了,更多相關(guān)JavaScript 工具函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JS中比較兩個(gè)Object數(shù)組是否相等方法實(shí)例
在本篇文章里小編給大家整理的是一篇關(guān)于JS中比較兩個(gè)Object數(shù)組是否相等方法實(shí)例內(nèi)容,有需要的朋友們學(xué)習(xí)下。2019-11-11PHP配置文件php.ini中打開錯(cuò)誤報(bào)告的設(shè)置方法
這篇文章主要介紹了PHP配置文件php.ini中打開錯(cuò)誤報(bào)告的設(shè)置方法,需要的朋友可以參考下2015-01-01子窗口、父窗口和Silverlight之間的相互調(diào)用
前兩天做 silverlight 的東西,主頁面打開一個(gè)子頁面,然后子頁面中包含一個(gè) silverlight 應(yīng)用程序那難免會(huì)涉及到他們?nèi)呦嗷フ{(diào)用的問題2010-08-08JavaScript二維數(shù)組實(shí)現(xiàn)的省市聯(lián)動(dòng)菜單
這篇文章主要介紹了使用二維數(shù)組實(shí)現(xiàn)的省市聯(lián)動(dòng)菜單,通過二維數(shù)組存儲(chǔ)城市列表項(xiàng),需要的朋友可以參考下2014-05-05