Leanote's Blog
I love Leanote!
Toggle navigation
Leanote's Blog
Home
Chrome
Git
Linux
Windows
Others
工具大全
VsCode
Expo
Html
JavaScript
Npm
Node
Mock
React-Native
React
TypeScript
小程序
插件
正则
Dva
Ant-Design-React
Umi
Vue
Vux
Ant-Design-Vue
Http
Java
flutter
开发小工具
About Me
Archives
Tags
js常用工具函数
2021-06-09 02:10:33
6
0
0
admin
``` /** * 复制文本 * @param text */ export function copyText(text) { const input = document.createElement("input") input.value = text document.body.appendChild(input) input.select() document.execCommand("Copy") window.setTimeout(function () { document.body.removeChild(input) }, 0) } /** * esc监听全屏 */ export const listenfullscreen = (callback) => { function listen() { callback() } document.addEventListener("fullscreenchange", function () { listen() }) document.addEventListener("mozfullscreenchange", function () { listen() }) document.addEventListener("webkitfullscreenchange", function () { listen() }) document.addEventListener("msfullscreenchange", function () { listen() }) } /** * 浏览器判断是否全屏 */ export const fullscreenEnable = () => { return document.isFullScreen || document.mozIsFullScreen || document.webkitIsFullScreen } /** * 浏览器全屏 */ export const reqFullScreen = () => { if (document.documentElement.requestFullScreen) { document.documentElement.requestFullScreen() } else if (document.documentElement.webkitRequestFullScreen) { document.documentElement.webkitRequestFullScreen() } else if (document.documentElement.mozRequestFullScreen) { document.documentElement.mozRequestFullScreen() } } /** * 浏览器退出全屏 */ export const exitFullScreen = () => { if (document.documentElement.requestFullScreen) { document.exitFullScreen() } else if (document.documentElement.webkitRequestFullScreen) { document.webkitCancelFullScreen() } else if (document.documentElement.mozRequestFullScreen) { document.mozCancelFullScreen() } } /** * 递归寻找子类的父类 */ export const findParent = (menu, id) => { for (let i = 0; i < menu.length; i++) { if (menu[i].children.length !== 0) { for (let j = 0; j < menu[i].children.length; j++) { if (menu[i].children[j].id === id) { return menu[i] } else { if (menu[i].children[j].children.length !== 0) { return findParent(menu[i].children[j].children, id) } } } } } } /** * 动态插入css */ export const loadStyle = url => { const link = document.createElement("link") link.type = "text/css" link.rel = "stylesheet" link.href = url const head = document.getElementsByTagName("head")[0] head.appendChild(link) } /** * 判断路由是否相等 */ export const isObjectValueEqual = (a, b) => { let result = true Object.keys(a).forEach(ele => { const type = typeof (a[ele]) if (type === "string" && a[ele] !== b[ele]) result = false else if (type === "object" && JSON.stringify(a[ele]) !== JSON.stringify(b[ele])) result = false }) return result } /** * 根据字典的value显示label */ export const findByvalue = (dic, value) => { let result = "" if (validatenull(dic)) return value if (typeof (value) === "string" || typeof (value) === "number" || typeof (value) === "boolean") { let index = 0 index = findArray(dic, value) if (index !== -1) { result = dic[index].label } else { result = value } } else if (value instanceof Array) { result = [] let index = 0 value.forEach(ele => { index = findArray(dic, ele) if (index !== -1) { result.push(dic[index].label) } else { result.push(value) } }) result = result.toString() } return result } /** * 根据字典的value查找对应的index */ export const findArray = (dic, value) => { for (let i = 0; i < dic.length; i++) { if (dic[i].value === value) { return i } } return -1 } /** * 生成随机len位数字 */ export const randomLenNum = (len, date) => { let random = "" random = Math.ceil(Math.random() * 100000000000000).toString().substr(0, len || 4) if (date) random = random + Date.now() return random } /** * 打开小窗口 */ export const openWindow = (url, title, w, h) => { // Fixes dual-screen position Most browsers Firefox const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left const dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height const left = ((width / 2) - (w / 2)) + dualScreenLeft const top = ((height / 2) - (h / 2)) + dualScreenTop const newWindow = window.open(url, title, "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, copyhistory=no, width=" + w + ", height=" + h + ", top=" + top + ", left=" + left) // Puts focus on the newWindow if (window.focus) { newWindow.focus() } } /** * <img> <a> src 处理 * @returns {PromiseLike<T | never> | Promise<T | never>} */ export function handleImg(url, id) { return validatenull(url) ? null : request({ url: url, method: "get", responseType: "blob" }).then((response) => { // 处理返回的文件流 const blob = response.data if (blob) { const img = document.getElementById(id) if (img) { img.src = URL.createObjectURL(blob) window.setTimeout(function () { window.URL.revokeObjectURL(blob) }, 0) } } }) } /** * 下载文件 */ export function handleDown(filename, bucket) { return request({ url: "/admin/sys-file/" + bucket + "/" + filename, method: "get", responseType: "blob" }).then((response) => { // 处理返回的文件流 const blob = response.data const link = document.createElement("a") link.href = URL.createObjectURL(blob) link.download = filename document.body.appendChild(link) link.click() window.setTimeout(function () { URL.revokeObjectURL(blob) document.body.removeChild(link) }, 0) }) } /** * 金额处理 */ export function fmoney(s, n) { n = n > 0 && n <= 20 ? n : 2 s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "" let l = s.split(".")[0].split("").reverse(), r = s.split(".")[1] let t = "" for (let i = 0; i < l.length; i++) { t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "") } return t.split("").reverse().join("") + "." + r } /** * 转url参数 */ export function getQueryString(url, paraName) { const arrObj = url.split("?") if (arrObj.length > 1) { const arrPara = arrObj[1].split("&") let arr for (let i = 0; i < arrPara.length; i++) { arr = arrPara[i].split("=") // eslint-disable-next-line eqeqeq if (arr != null && arr[0] == paraName) { return arr[1] } } return "" } else { return "" } } /** * img转Base64 */ export function imgToBase64(imgSrcc, imgName) { let imgSrc = imgSrcc + "?" + new Date().getTime() let imgType = "image/png" if (!imgName) { const arr = imgSrc.split("/") const imgMsgArr = arr[arr.length - 1].split(".") imgName = imgMsgArr[0] if (imgMsgArr[1]) imgType = "image/" + imgMsgArr[1] } let image = new Image() image.setAttribute("crossOrigin", "anonymous") image.onload = function () { const canvas = document.createElement("canvas") canvas.width = image.width canvas.height = image.height const context = canvas.getContext("2d") context.drawImage(image, 0, 0, image.width, image.height) const url = canvas.toDataURL(imgType) let a = document.createElement("a") a.download = imgName || "图片" a.href = url a.click() a = null } image.src = imgSrc } /** * 复制文本 */ export function copyText(text) { const input = document.createElement("input") input.value = text document.body.appendChild(input) input.select() document.execCommand("Copy") window.setTimeout(function () { document.body.removeChild(input) }, 0) } /** * 合并弹窗信息 (临时方案) * @param message * @param type */ export const debounceMessage = _.debounce(function (options) { Message(options) }, 500) /** * 时间范围验证 * @param {type} rbTime "时:分:秒" * @param {type} reTime "时:分:秒" * @param {type} vbTime 正确的时间戳或字符串 * @param {type} veTime 正确的时间戳或字符串 */ export function timeRangeValitor(rbTime = "", reTime = "", vbTime = "", veTime = "") { const newValueBeginTime = new Date(vbTime.replace(/-/g, "/")) const newValueEndTime = new Date(veTime.replace(/-/g, "/")) const oldRangeBeginTime = new Date(vbTime.replace(/-/g, "/")) rbTime.split(":").forEach((i, idx) => { if (idx == 0) { oldRangeBeginTime.setHours(i) } else if (idx == 1) { oldRangeBeginTime.setMinutes(i) } else if (idx == 2) { oldRangeBeginTime.setSeconds(i) } }) const oldRangeEndTime = new Date(veTime.replace(/-/g, "/")) reTime.split(":").forEach((i, idx) => { if (idx == 0) { oldRangeEndTime.setHours(i) } else if (idx == 1) { oldRangeEndTime.setMinutes(i) } else if (idx == 2) { oldRangeEndTime.setSeconds(i) } }) if ( (newValueBeginTime >= oldRangeBeginTime && newValueBeginTime < oldRangeEndTime) || (newValueBeginTime < oldRangeBeginTime && newValueEndTime > oldRangeEndTime) || (newValueEndTime > oldRangeBeginTime && newValueEndTime <= oldRangeEndTime) ) { return true } return false } /** * 同步执行操作,Currying * @param {*} action 要执行的操作 * @param {function} cb 下一步操作回调 */ export const asyncAction = (action: unknown | void) => { const wait = new Promise((resolve) => { resolve(action) }) return (cb: () => void) => { wait.then(() => setTimeout(() => cb())) } } /** * 获取地址栏 ?参数,返回键值对对象 */ export const getQuery = (): CommonObjectType<string> => { const { href } = window.location const query = href.split('?') if (!query[1]) return {} const queryArr = decodeURI(query[1]).split('&') const queryObj = queryArr.reduce((prev, next) => { const item = next.split('=') return { ...prev, [item[0]]: item[1] } }, {}) return queryObj } /** * 深拷贝操作,简单类型的对象的可以直接用 JSON.parse(JSON.stringify())或 [...]/{...} * @param {object} obj 需要拷贝的对象 */ export const deepClone = (obj: CommonObjectType) => { if ( obj === null || typeof obj !== 'object' || obj instanceof Date || obj instanceof Function ) { return obj } const cloneObj = Array.isArray(obj) ? [] : {} Object.keys(obj).map((key) => { cloneObj[key] = deepClone(obj[key]) return cloneObj }) return cloneObj } /** * 富文本字符串里面获取图片地址 * @param {*} html 富文本字符串 */ export const getImgsUrl = (html?: string) => { // 匹配图片(g表示匹配所有结果i表示区分大小写) const imgReg = /<img.*?(?:>|\/>)/gi // 匹配src属性 const srcReg = /src=['"]?([^'"]*)['"]?/i const arr = html.match(imgReg) if (!arr) return null // 获取图片地址 const urlArr = arr.reduce((prev, next) => { const src = next.match(srcReg) return src[1] ? [...prev, src[1]] : prev }, []) return urlArr } /** * 富文本字符串里面获取视频地址 * @param {*} html 富文本字符串 */ export const getVideoUrl = (html?: string) => { // 匹配图片(g表示匹配所有结果i表示区分大小写) const imgReg = /<(video|iframe).*?(?:>|\/>)/gi // 匹配src属性 const srcReg = /src=['"]?([^'"]*)['"]?/i const arr = html.match(imgReg) if (!arr) return null // 获取图片地址 const urlArr = arr.reduce((prev, next) => { const src = next.match(srcReg) return src[1] ? [...prev, src[1]] : prev }, []) return urlArr } /** * 用requestAnimationFrame替代setTimeout、setInterval,解决内存溢出 * @export * @param {*} cb 定时回调 * @param {*} interval 定时时间 */ export const customTimer = { intervalTimer: null, timeoutTimer: null, setTimeout(cb: () => void, interval: number) { // 实现setTimeout功能 const { now } = Date const stime = now() let etime = stime const loop = () => { this.timeoutTimer = requestAnimationFrame(loop) etime = now() if (etime - stime >= interval) { cb() cancelAnimationFrame(this.timeoutTimer) } } this.timeoutTimer = requestAnimationFrame(loop) return this.timeoutTimer }, clearTimeout() { cancelAnimationFrame(this.timeoutTimer) }, setInterval(cb: () => void, interval: number) { // 实现setInterval功能 const { now } = Date let stime = now() let etime = stime const loop = () => { this.intervalTimer = requestAnimationFrame(loop) etime = now() if (etime - stime >= interval) { stime = now() etime = stime cb() } } this.intervalTimer = requestAnimationFrame(loop) return this.intervalTimer }, clearInterval() { cancelAnimationFrame(this.intervalTimer) } } /** * 限制两位小数,可 ± * @param {string} val 要格式化的数字 */ export const limitDecimal = (val: string) => val.replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3') /** * 批量ZIP压缩下载文件 */ import JSZip from 'jszip'; import FileSaver from 'file-saver'; /** * 批量ZIP压缩下载文件 * @param urlList 地址数组 * @param fileName 压缩包名, 默认为批量下载.zip * @returns {Promise<Awaited<unknown>[]>} */ export function handleBatchZIPDownload(urlList, fileName = '批量下载.zip') { const data = urlList; // 需要下载打包的路径, 可以是本地相对路径, 也可以是跨域的全路径 const zip = new JSZip(); const cache = {}; const promises = []; data.forEach(item => { const promise = fetch(item, { responseType: 'blob', }).then(res => { // 下载文件, 并存成ArrayBuffer对象 const blob = res.blob(); const arr_name = item.split('/'); const file_name = arr_name[arr_name.length - 1]; // 获取文件名 zip.file(file_name, blob, { binary: true }); // 逐个添加文件 cache[file_name] = blob; }); promises.push(promise); }); return Promise.all(promises).then(() => { zip.generateAsync({ type: 'blob' }).then(content => { // 生成二进制流 FileSaver.saveAs(content, fileName); // 利用file-saver保存文件 }); }); } /** * 随机生成颜色 */ function randomRGB(min = 100, max = 230) { // 定义三个变量,存储三种颜色的值 等于随机生成的数,在min ~ max 之间 const color1 = parseInt(Math.random() * (max - min + 1) + min, 10) const color2 = parseInt(Math.random() * (max - min + 1) + min, 10) const color3 = parseInt(Math.random() * (max - min + 1) + min, 10) // 最终返回是一个字符串,用rgb(100, 100, 100) 的形式 所以需要拼接 return 'rgb(' + color1 + ',' + color2 + ',' + color3 + ')' } /** * 同步加载script * @param url * @returns {Promise<unknown>} */ loadScriptSync(url) { return new Promise((resolve, reject) => { try { const script = document.createElement('script') if (script.readyState) { // IE script.onreadystatechange = function () { if (script.readyState === 'loaded' || script.readyState === 'complete') { script.onreadystatechange = null resolve() } } } else { // 其他浏览器 script.onload = function () { resolve() } } script.type = 'text/javascript' script.src = url document.getElementsByTagName('head')[0].appendChild(script) } catch (err) { const msg = typeof err === 'object' ? err.message : err reject(msg) } }) }, /** * 异步加载script * @param url */ loadScript(url) { try { const script = document.createElement('script') script.type = 'text/javascript' script.src = url document.getElementsByTagName('head')[0].appendChild(script) } catch (err) { console.error(err) } } ```
Pre:
Vue拖拽Draggable插件
Next:
$once清除定时器
0
likes
6
Weibo
Wechat
Tencent Weibo
QQ Zone
RenRen
Submit
Sign in
to leave a comment.
No Leanote account?
Sign up now.
0
comments
More...
Table of content
No Leanote account? Sign up now.