您好,登錄后才能下訂單哦!
這篇文章主要介紹了高頻使用的JS工具有哪些的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇高頻使用的JS工具有哪些文章都會有所收獲,下面我們一起來看看吧。
較為平滑的回到頂部方案
const scrollToTop = () => { const c = document.documentElement.scrollTop || document.body.scrollTop; if (c > 0) { window.requestAnimationFrame(scrollToTop); window.scrollTo(0, c - c / 8); } }; scrollToTop();
項目中經常會使用的工具方法,傳入目標數組和目標元素,返回一個新數組。
const removeArray = (arr, item) => { let result = []; let index = -1; if (!(arr != null && arr.length)) { return result; } result = arr; if (Object.prototype.toString.call(item) == "[object Object]") { index = arr.findIndex((i) => isEqualObject(i, item)); } else { index = arr.findIndex((i) => i === item); } if (index > -1) result.splice(index, 1); return result; }; const isEqualObject = (obja, objb) => { const aProps = Object.getOwnPropertyNames(obja); const bProps = Object.getOwnPropertyNames(objb); if (aProps.length != bProps.length) { return false; } for (let i = 0; i < aProps.length; i++) { let propName = aProps[i]; let propA = obja[propName]; let propB = objb[propName]; if (!objb.hasOwnProperty(propName)) return false; if (propA instanceof Object) { if (!this.isEqualObject(propA, propB)) { return false; } } else if (propA !== propB) { return false; } } return true; }; removeArray([{ name: 1 }, { name: "1" }, 1, "1"], { name: "1" });
用于獲取url傳參獲取參數
const getUrlParam = (key) => { const url = new URL(window.location.href); const value = url.searchParams.get(key); return value; }; getUrlParam("id");
復制各種自定義的文本,瀏覽器兼容性高
const copyText = (text) => { const clipboardData = window.clipboardData; if (clipboardData) { clipboardData.clearData(); clipboardData.setData("Text", text); return true; } else if (document.execCommand) { const el = document.createElement("textarea"); el.value = text; el.setAttribute("readonly", ""); el.style.position = "absolute"; el.style.left = "-9999px"; document.body.appendChild(el); el.select(); document.execCommand("copy"); document.body.removeChild(el); return true; } return false; }; copyText("Test");
body { user-select: none; -moz-user-select: none; -webkit-user-select: none; -ms-user-select: none; }
// 禁止右鍵菜單 document.body.oncontextmenu = (e) => { return false; }; // 禁止選中文字 document.body.onselectstart = (e) => { return false; }; // 禁止復制 document.body.oncopy = (e) => { return false; }; // 禁止剪切 document.body.oncut = (e) => { return false; }; // 禁止粘貼 document.body.onpaste = (e) => { return false; };
document.body.oncopy = (event) => { event.preventDefault(); const clipboardData = event.clipboardData; let text = window.getSelection(0).toString(); text = `${text}\n這是插入的文本\n 作者:于五五\n`; if (clipboardData) { clipboardData.clearData(); clipboardData.setData("Text", text); return true; } else if (document.execCommand) { window.clipboardData.setData("Text", text); } return false; };
很常用的工具類,用于校驗數據是否合法
// 是否是字符串 function isString(obj) { return Object.prototype.toString.call(obj) == "[object String]"; } // 是否是數字 function isNumber(obj) { return ( Object.prototype.toString.call(obj) == "[object Number]" && /[\d\.]+/.test(String(obj)) ); } // 是否是布爾 function isBoolean(obj) { return Object.prototype.toString.call(obj) == "[object Boolean]"; } // 是否是數組 function isArray(obj) { return Object.prototype.toString.call(obj) === "[object Array]"; } // 是否是對象 function isObject(arg) { if (arg == null) { return false; } else { return Object.prototype.toString.call(arg) == "[object Object]"; } } // 是否是方法 function isFunction(arg) { const type = Object.prototype.toString.call(arg); return type == "[object Function]" || type == "[object AsyncFunction]"; } // 是否是時間格式 function isDate(obj) { return Object.prototype.toString.call(obj) == "[object Date]"; } // 是否是時間undefined function isUndefined(arg) { return arg === void 0; } // 是否是空對象 function isEmptyObject(arg) { if (isObject(arg)) { for (var key in arg) { if (Object.prototype.hasOwnProperty.call(arg, key)) { return false; } } return true; } return false; }
用來區分不同平臺,常用在ios端做適配
const getUaInfo = () => { const ua = navigator.userAgent.toLowerCase(); const Agents = [ "Android", "android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod", ]; let isPc = true; for (var i = 0; i < Agents.length; i++) { if (userAgentInfo.includes(Agents[i])) { isPc = false; break; } } return { // 是不是ios isIos: !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) || ua.includes("mac os x"), // 是不是安卓 isAndroid: ua.includes("android") || ua.includes("Android") || ua.includes("Adr"), // 是不是微信環境 isWeixin: ua.match(/MicroMessenger/i) == "micromessenger", // 是不是電腦端 isPc: isPc, }; };
// Date轉yyyy-MM-dd HH:mm:ss const filterTimeByDate = (date, pattern = "yyyy-MM-dd HH:mm:ss") => { const o = { "M+": date.getMonth() + 1, "d+": date.getDate(), "H+": date.getHours(), "m+": date.getMinutes(), "s+": date.getSeconds(), "q+": Math.floor((date.getMonth() + 3) / 3), S: date.getMilliseconds(), }; if (/(y+)/.test(pattern)) { pattern = pattern.replace( RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length) ); } for (var k in o) { if (new RegExp("(" + k + ")").test(pattern)) { pattern = pattern.replace( RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length) ); } } return pattern; }; filterTimeByDate(new Date()); // 時間戳轉yyyy-MM-dd HH:mm:ss const timestampToTime = (timestamp) => { const date = new Date( String(timestamp).length > 10 ? timestamp : timestamp * 1000 ); //時間戳為10位需*1000,時間戳為13位的話不需乘1000 const Y = date.getFullYear() + "-"; const M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-"; const D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " "; const h = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":"; const m = (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":"; const s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); return Y + M + D + h + m + s; }; timestampToTime(new Date().getTime()); // yyyy-MM-dd HH:mm:ss轉時間戳 const timeToTimestamp = (time, isMilli = true) => { const timestamp = new Date(time).getTime(); //時間戳為10位需*1000,時間戳為13位的話不需乘1000 return isMilli ? timestamp : timestamp / 1000; }; timeToTimestamp("2022-04-26 10:11:11");
const debounce = (fn, delay) => { let timer = null; return function (e) { clearTimeout(timer); timer = setTimeout(() => { fn.apply(this, arguments); }, delay); }; }; document.addEventListener( "scroll", debounce(function () { console.log("執行"); }, 2000) );
function toFullScreen() { let = document.documentElement; el.webkitRequestFullScreen ? el.webkitRequestFullScreen() : el.mozRequestFullScreen ? el.mozRequestFullScreen() : el.msRequestFullscreen ? el.msRequestFullscreen() : el.requestFullScreen ? el.requestFullScreen() : alert("當前瀏覽器不支持該功能"); } function exitFullscreen() { let el = document; el.webkitCancelFullScreen ? el.webkitCancelFullScreen() : el.mozCancelFullScreen ? el.mozCancelFullScreen() : el.cancelFullScreen ? el.cancelFullScreen() : el.msExitFullscreen ? el.msExitFullscreen() : el.exitFullscreen ? el.exitFullscreen() : alert("當前瀏覽器不支持該功能"); }
用來防止部分用戶通過源碼攻擊服務器,增加破解難度
setInterval(function () { check(); }, 4000); const check = () => { function doCheck(a) { if (("" + a / a)["length"] !== 1 || a % 20 === 0) { (function () {}["constructor"]("debugger")()); } else { (function () {}["constructor"]("debugger")()); } doCheck(++a); } try { doCheck(0); } catch (err) {} }; check();
const checkPwd = (str) => { let Lv = 0; if (str.length < 6) { return Lv; } if (/[0-9]/.test(str)) { Lv++; } if (/[a-z]/.test(str)) { Lv++; } if (/[A-Z]/.test(str)) { Lv++; } if (/[\.|-|_]/.test(str)) { Lv++; } return Lv; };
const getRate = (rate = 0) => { return "★★★★★☆☆☆☆☆".slice(5 - rate, 10 - rate); }; getRate(3);
const filterToFixed => (num, n = 2) { return parseFloat(num.toFixed(n), 10); }
商城項目里訂單模塊很常用的工具方法
const convertCurrency = (money) => { //漢字的數字 const cnNums = new Array( "零", "壹", "貳", "叁", "肆", "伍", "陸", "柒", "捌", "玖" ); //基本單位 const cnIntRadice = new Array("", "拾", "佰", "仟"); //對應整數部分擴展單位 const cnIntUnits = new Array("", "萬", "億", "兆"); //對應小數部分單位 const cnDecUnits = new Array("角", "分", "毫", "厘"); //整數金額時后面跟的字符 const cnInteger = "整"; //整型完以后的單位 const cnIntLast = "元"; //最大處理的數字 const maxNum = 999999999999999.9999; //金額整數部分 let integerNum; //金額小數部分 let decimalNum; //輸出的中文金額字符串 let chineseStr = ""; //分離金額后用的數組,預定義 let parts; // 傳入的參數為空情況 if (money == "") { return ""; } money = parseFloat(money); if (money >= maxNum) { return ""; } // 傳入的參數為0情況 if (money == 0) { chineseStr = cnNums[0] + cnIntLast + cnInteger; return chineseStr; } // 轉為字符串 money = money.toString(); // indexOf 檢測某字符在字符串中首次出現的位置 返回索引值(從0 開始) -1 代表無 if (money.indexOf(".") == -1) { integerNum = money; decimalNum = ""; } else { parts = money.split("."); integerNum = parts[0]; decimalNum = parts[1].substr(0, 4); } //轉換整數部分 if (parseInt(integerNum, 10) > 0) { let zeroCount = 0; let IntLen = integerNum.length; for (let i = 0; i < IntLen; i++) { let n = integerNum.substr(i, 1); let p = IntLen - i - 1; let q = p / 4; let m = p % 4; if (n == "0") { zeroCount++; } else { if (zeroCount > 0) { chineseStr += cnNums[0]; } zeroCount = 0; chineseStr += cnNums[parseInt(n)] + cnIntRadice[m]; } if (m == 0 && zeroCount < 4) { chineseStr += cnIntUnits[q]; } } // 最后+ 元 chineseStr += cnIntLast; } // 轉換小數部分 if (decimalNum != "") { let decLen = decimalNum.length; for (let i = 0; i < decLen; i++) { let n = decimalNum.substr(i, 1); if (n != "0") { chineseStr += cnNums[Number(n)] + cnDecUnits[i]; } } } if (chineseStr == "") { chineseStr += cnNums[0] + cnIntLast + cnInteger; } else if (decimalNum == "") { chineseStr += cnInteger; } return chineseStr; };
// 校驗昵稱為2-9位中文 const validateName = (name) => { const reg = /^[\u4e00-\u9fa5]{2,9}$/; return reg.test(name); }; // 校驗手機號 const validateMobile = (mobile) => { const reg = /^1[3,4,5,6,7,8,9]\d{9}$/; return reg.test(mobile); }; // 校驗6到18位大小寫字母數字下劃線組成的密碼 const validatePassword = (password) => { const reg = /^[a-zA-Z0-9_]{6,18}$/; return reg.test(password); }; // 校驗身份證號 const validateCardId = (cardId) => { const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/; return reg.test(cardId); };
用來解決前端計算金額時精度丟失的問題
const calculation = { // 加法 plus(arg1, arg2) { var r1, r2, m; try { r1 = arg1.toString().split(".")[1].length; } catch (e) { r1 = 0; } try { r2 = arg2.toString().split(".")[1].length; } catch (e) { r2 = 0; } m = Math.pow(10, Math.max(r1, r2)); return (arg1 * m + arg2 * m) / m; }, //減法 subtract(arg1, arg2) { var r1, r2, m, n; try { r1 = arg1.toString().split(".")[1].length; } catch (e) { r1 = 0; } try { r2 = arg2.toString().split(".")[1].length; } catch (e) { r2 = 0; } m = Math.pow(10, Math.max(r1, r2)); n = r1 >= r2 ? r1 : r2; return ((arg1 * m - arg2 * m) / m).toFixed(n); }, // 乘法 multiply(arg1, arg2) { var m = 0, s1 = arg1.toString(), s2 = arg2.toString(); try { m += s1.split(".")[1].length; } catch (e) {} try { m += s2.split(".")[1].length; } catch (e) {} return ( (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) / Math.pow(10, m) ); }, // 除法 divide(arg1, arg2) { var t1 = 0, t2 = 0, r1, r2; try { t1 = arg1.toString().split(".")[1].length; } catch (e) {} try { t2 = arg2.toString().split(".")[1].length; } catch (e) {} r1 = Number(arg1.toString().replace(".", "")); r2 = Number(arg2.toString().replace(".", "")); return (r1 / r2) * Math.pow(10, t2 - t1); }, };
關于“高頻使用的JS工具有哪些”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“高頻使用的JS工具有哪些”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。