日常开发中js工具方法
1. 浏览器操作
(1)滚动到页面顶部
export const scrollToTop = () => {
const height = document.documentElement.scrollTop || document.body.scrollTop;
if (height > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, height - height / 8);
}
}
(2)滚动到页面底部
export const scrollToBottom = () => {
window.scrollTo(0, document.documentElement.clientHeight);
}
(3)滚动到指定元素区域
export const smoothScroll = (element) => {
document.querySelector(element).scrollIntoView({
behavior: 'smooth'
});
};
(4)获取可视窗口高度
export const getClientHeight = () => {
let clientHeight = 0;
if (document.body.clientHeight && document.documentElement.clientHeight) {
clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight;
}
else {
clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight;
}
return clientHeight;
}
(5)获取可视窗口宽度
export const getPageViewWidth = () => {
return (document.compatMode == "BackCompat" ? document.body : document.documentElement).clientWidth;
}
(6)打开浏览器全屏
export const toFullScreen = () => {
let element = document.body;
if (element.requestFullscreen) {
element.requestFullscreen()
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen()
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen()
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullScreen()
}
}
(7)退出浏览器全屏
export const exitFullscreen = () => {
if (document.exitFullscreen) {
document.exitFullscreen()
} else if (document.msExitFullscreen) {
document.msExitFullscreen()
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen()
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen()
}
}
2.判断数据类型和数据值
(1)是否是字符串
function isString(obj) {
return Object.prototype.toString.call(obj) == "[object String]";
}
(2)是否是数字
function isNumber(obj) {
return (
Object.prototype.toString.call(obj) == "[object Number]" &&
/[\d\.]+/.test(String(obj))
);
}
(3)是否是布尔
function isBoolean(obj) {
return Object.prototype.toString.call(obj) == "[object Boolean]";
}
(4)是否是数组
function isArray(obj) {
return Object.prototype.toString.call(obj) === "[object Array]";
}
(5)是否是对象
function isObject(arg) {
if (arg == null) {
return false;
} else {
return Object.prototype.toString.call(arg) == "[object Object]";
}
}
(6)是否是方法
function isFunction(arg) {
const type = Object.prototype.toString.call(arg);
return type == "[object Function]" || type == "[object AsyncFunction]";
}
(7)是否是时间格式
function isDate(obj) {
return Object.prototype.toString.call(obj) == "[object Date]";
}
(8)是否是时间undefined
function isUndefined(arg) {
return arg === void 0;
}
(9)是否是空对象
function isEmptyObject(arg) {
if (isObject(arg)) {
for (var key in arg) {
if (Object.prototype.hasOwnProperty.call(arg, key)) {
return false;
}
}
return true;
}
return false;
}
3.设备判断
(1)判断是移动还是PC设备
export const isMobile = () => {
if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone)/i))) {
return 'mobile';
}
return 'desktop';
}
(2)判断是否是苹果还是安卓移动设备
export const isAppleMobileDevice = () => {
let reg = /iphone|ipod|ipad|Macintosh/i;
return reg.test(navigator.userAgent.toLowerCase());
}
(3)判断是否是安卓移动设备
export const isAndroidMobileDevice = () => {
return /android/i.test(navigator.userAgent.toLowerCase());
}
(4)判断是Windows还是Mac系统
export const osType = () => {
const agent = navigator.userAgent.toLowerCase();
const isMac = /macintosh|mac os x/i.test(navigator.userAgent);
const isWindows = agent.indexOf("win64") >= 0 || agent.indexOf("wow64") >= 0 || agent.indexOf("win32") >= 0 || agent.indexOf("wow32") >= 0;
if (isWindows) {
return "windows";
}
if(isMac){
return "mac";
}
}
(5)判断是否是微信/QQ内置浏览器
export const broswer = () => {
const ua = navigator.userAgent.toLowerCase();
if (ua.match(/MicroMessenger/i) == "micromessenger") {
return "weixin";
} else if (ua.match(/QQ/i) == "qq") {
return "QQ";
}
return false;
}
(6)浏览器型号和版本
export const getExplorerInfo = () => {
let t = navigator.userAgent.toLowerCase();
return 0 <= t.indexOf("msie") ? { //ie < 11
type: "IE",
version: Number(t.match(/msie ([\d]+)/)[1])
} : !!t.match(/trident\/.+?rv:(([\d.]+))/) ? { // ie 11
type: "IE",
version: 11
} : 0 <= t.indexOf("edge") ? {
type: "Edge",
version: Number(t.match(/edge\/([\d]+)/)[1])
} : 0 <= t.indexOf("firefox") ? {
type: "Firefox",
version: Number(t.match(/firefox\/([\d]+)/)[1])
} : 0 <= t.indexOf("chrome") ? {
type: "Chrome",
version: Number(t.match(/chrome\/([\d]+)/)[1])
} : 0 <= t.indexOf("opera") ? {
type: "Opera",
version: Number(t.match(/opera.([\d]+)/)[1])
} : 0 <= t.indexOf("Safari") ? {
type: "Safari",
version: Number(t.match(/version\/([\d]+)/)[1])
} : {
type: t,
version: -1
}
}
4.时间格式转换
(1)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());
(2)时间戳转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());
(3)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");
5.保留 n 位小数
const filterToFixed => (num, n = 2) {
return parseFloat(num.toFixed(n), 10);
}
6.常用正则判断
// 校验昵称为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);
};
//校验是否为中国大陆的邮政编码
export const isPostCode = (value) => {
return /^[1-9][0-9]{5}$/.test(value.toString());
}
//校验是否为邮箱地址
export const isEmail = (value) {
return /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value);
}
7.解决运算精度丢失的问题
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);
},
};
8.操作存储
(1)存储loalStorage
export const loalStorageSet = (key, value) => {
if (!key) return;
if (typeof value !== 'string') {
value = JSON.stringify(value);
}
window.localStorage.setItem(key, value);
};
(2)获取localStorage
export const loalStorageGet = (key) => {
if (!key) return;
return window.localStorage.getItem(key);
};
(3)删除localStorage
export const loalStorageRemove = (key) => {
if (!key) return;
window.localStorage.removeItem(key);
};
(4)存储sessionStorage
export const sessionStorageSet = (key, value) => {
if (!key) return;
if (typeof value !== 'string') {
value = JSON.stringify(value);
}
window.sessionStorage.setItem(key, value)
};
(5)获取sessionStorage
export const sessionStorageGet = (key) => {
if (!key) return;
return window.sessionStorage.getItem(key)
};
(6)删除sessionStorage
export const sessionStorageRemove = (key) => {
if (!key) return;
window.sessionStorage.removeItem(key)
};