以下代码均使用 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) {
// 加载js || css || style
let ref;
if (type === "js") {
// 外部js
ref = document.createElement("script");
ref.setAttribute("type", "text/javascript");
ref.setAttribute("src", name);
} else if (type === "css") {
// 外部css
ref = document.createElement("link");
ref.setAttribute("rel", "stylesheet");
ref.setAttribute("type", "text/css");
ref.setAttribute("href", name);
} else if (type === "style") {
// 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; // 时间,默认存储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();
}
},
};
export default {
store: store,
};
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) {
// 【'yyyy-MM-dd hh:mm:ss',时间】
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) {
// ajax操作
let url = conf.url,
data = conf.data,
senData = [], // 封装后的数据
async = conf.async !== undefined ? conf.async : true, // ture为异步请求
type = conf.type || "get", // 默认请求方式get
dataType = conf.dataType || "json",
contenType = conf.contenType || "application/x-www-form-urlencoded",
success = conf.success,
error = conf.error,
isForm = conf.isForm || false, // 是否formdata
header = conf.header || {}, // 头部信息
xhr = ""; // 创建ajax引擎对象
if (data == null) {
senData = "";
} else if (typeof data === "object" && !isForm) {
// 如果data是对象,转换为字符串
for (var k in data) {
senData.push(encodeURIComponent(k) + "=" + encodeURIComponent(data[k]));
}
senData = senData.join("&");
} else {
senData = data;
}
try {
xhr = new ActiveXObject("microsoft.xmlhttp"); // IE内核系列浏览器
} catch (e1) {
try {
xhr = new XMLHttpRequest(); // 非IE内核浏览器
} 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); // 将json字符串转换为js对象
}
} 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) {
// fetch请求的封装
let opts = {
// 设置参数的初始值
method: (setting.method || "GET").toUpperCase(), // 请求方式
headers: setting.headers || {}, // 请求头设置
credentials: setting.credentials || true, // 设置cookie是否一起发送
body: setting.body || {},
mode: setting.mode || "no-cors", // 可以设置 cors, no-cors, same-origin
redirect: setting.redirect || "follow", // follow, error, manual
cache: setting.cache || "default", // 设置 cache 模式 (default, reload, no-cache)
};
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) => {
// 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)) {
// ios
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,
};