以下代码均使用 es6 的 export defaule 导出方法,可以根据实际需求自行转换
动态加载 静态 js/css/style 资源
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| const loadRes = function (name, type, fn) { let ref; if (type === "js") { ref = document.createElement("script"); ref.setAttribute("type", "text/javascript"); ref.setAttribute("src", name); } else if (type === "css") { ref = document.createElement("link"); ref.setAttribute("rel", "stylesheet"); ref.setAttribute("type", "text/css"); ref.setAttribute("href", name); } else if (type === "style") { ref = document.createElement("style"); ref.innerHTML = name; } if (typeof ref !== "undefined") { document.getElementsByTagName("head")[0].appendChild(ref); ref.onload = function () { typeof fn === "function" && fn(); }; } }; export default { loadRes: loadRes, };
|
获取 url 参数
1 2 3 4 5 6 7 8 9 10 11
| const getUrlParam = function (name) { let reg = new RegExp("(^|&?)" + name + "=([^&]*)(&|$)", "i"); let r = window.location.href.substr(1).match(reg); if (r != null) { return decodeURI(r[2]); } return undefined; }; export default { getUrlParam: getUrlParam, };
|
基于 localStorage 本地存储
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| const store = { set: function (name, value, day) { let d = new Date(); let time = 0; day = typeof day === "undefined" || !day ? 1 : day; 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) { localStorage.removeItem(name); } else { localStorage.clear(); } }, }; export default { store: store, };
|
cookie 相关操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| const cookie = { 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); }, }; export default { cookie: cookie, };
|
获取元素样式【支持内联】
1 2 3 4 5 6 7 8 9 10 11 12
| const getRealStyle = function (obj, styleName) { var realStyle = null; if (obj.currentStyle) { realStyle = obj.currentStyle[styleName]; } else if (window.getComputedStyle) { realStyle = window.getComputedStyle(obj, null)[styleName]; } return realStyle; }; export default { getRealStyle: getRealStyle, };
|
时间格式化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| const formatDate = function (fmt, date) { if (typeof date !== "object") { date = !date ? new Date() : new Date(date); } var 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(fmt)) { fmt = fmt.replace( RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length) ); } for (var k in o) { if (new RegExp("(" + k + ")").test(fmt)) { fmt = fmt.replace( RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length) ); } } return fmt; }; export default { formatDate: formatDate, };
|
ajax 请求封装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| const ajax = function (conf) { let url = conf.url, data = conf.data, senData = [], async = conf.async !== undefined ? conf.async : true, type = conf.type || "get", dataType = conf.dataType || "json", contenType = conf.contenType || "application/x-www-form-urlencoded", success = conf.success, error = conf.error, isForm = conf.isForm || false, header = conf.header || {}, xhr = ""; if (data == null) { senData = ""; } else if (typeof data === "object" && !isForm) { for (var k in data) { senData.push(encodeURIComponent(k) + "=" + encodeURIComponent(data[k])); } senData = senData.join("&"); } else { senData = data; } try { xhr = new ActiveXObject("microsoft.xmlhttp"); } catch (e1) { try { xhr = new XMLHttpRequest(); } catch (e2) { if (error != null) { error("不支持ajax请求"); } } } xhr.open(type, type !== "get" ? url : url + "?" + senData, async); if (type !== "get" && !isForm) { xhr.setRequestHeader("content-type", contenType); } for (var h in header) { xhr.setRequestHeader(h, header[h]); } xhr.send(type !== "get" ? senData : null); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status >= 200 && xhr.status < 300) { if (dataType === "json" && success != null) { let res = ""; try { res = eval("(" + xhr.responseText + ")"); } catch (e) { console.log(e); } success(res); } } else { if (error != null) { error("通讯失败!" + xhr.status); } } } }; }; export default { ajax: ajax, };
|
fetch 请求封装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| const fetch = function (url, setting) { let opts = { method: (setting.method || "GET").toUpperCase(), headers: setting.headers || {}, credentials: setting.credentials || true, body: setting.body || {}, mode: setting.mode || "no-cors", redirect: setting.redirect || "follow", cache: setting.cache || "default", }; let dataType = setting.dataType || "json"; let data = setting.data || ""; let paramsFormat = function (obj) { var str = ""; for (var i in obj) { str += `${i}=${obj[i]}&`; } return str.split("").slice(0, -1).join(""); };
if (opts.method === "GET") { url = url + (data ? `?${paramsFormat(data)}` : ""); } else { setting.body = data || {}; } return new Promise((resolve, reject) => { fetch(url, opts) .then(async (res) => { let data = dataType === "text" ? await res.text() : dataType === "blob" ? await res.blob() : await res.json(); resolve(data); }) .catch((e) => { reject(e); }); }); }; export default { fetch: fetch, };
|
axios 请求封装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| import axios from "axios"; export default class Server { axios(method, url, data) { return new Promise((resolve, reject) => { const _option = { method, url, timeout: 1000 * 300, params: null, data: data, headers: { "content-type": "application/json", }, validateStatus: (status) => { return status >= 200 && status < 300; }, }; axios.request(_option).then( (res) => { if (res.data.code != 0) { console.error("connent error"); } resolve( typeof res.data === "object" ? res.data : JSON.parse(res.data) ); }, (error) => { if (error.response) { reject(error.response.data); } else { reject(error); } }, axios.interceptors.response.use((response) => { return response; }) ); }).catch((res) => { return { msg: "connent error", }; }); } }
|
判断设备是 android 还是 ios 还是 web
1 2 3 4 5 6 7 8 9 10 11 12 13
| const isDevice = function () { if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) { return "iOS"; } if (/(Android)/i.test(navigator.userAgent)) { return "Android"; } return "Web"; }; export default { isDevice: isDevice, };
|
判断是否微信
1 2 3 4 5 6 7 8 9 10
| const isWx = function () { var ua = window.navigator.userAgent.toLowerCase(); if (ua.match(/MicroMessenger/i) === "micromessenger") { return true; } return false; }; export default { isWx: isWx, };
|
浏览器文本复制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| const copyTxt = function (text, fn) { if (typeof document.execCommand !== "function") { console.log("复制失败,请长按复制"); 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("复制成功"); typeof fn === "function" && fn(); return; } if (typeof document.createRange !== "function") { console.log("复制失败,请长按复制"); 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("复制成功"); }; export default { copyTxt: copyTxt, };
|
判断两个数组是否相等
1 2 3 4 5 6 7 8 9 10 11
| const arrayEqual = function (arr1, arr2) { if (arr1 === arr2) return true; if (arr1.length != arr2.length) return false; for (let i = 0; i < arr1.length; ++i) { if (arr1[i] !== arr2[i]) return false; } return true; }; export default { arrayEqual: arrayEqual, };
|