1.检测当前宿主环境是否是浏览器
const inBrowser = typeof window !== 'undefined'
2.获取当浏览器的user Agent
const UA = inBrowser && window.navigator.userAgent.toLowerCase()
3.IE浏览器判断
const isIE = UA && /msie|trident/.test(UA)
4.IE9| Edge | Chrome 判断
const isIE9 = UA && UA.indexOf('msie 9.0') > 0
const isEdge = UA && UA.indexOf('edge/') > 0
const isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge
5.连字符转驼峰
const camelizeRE = /-(\w)/g
const camelize = str => {
return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '')
})
6.将给定变量的值转换为 string 类型并返回
function toString (val) {
return val == null
? ''
: typeof val === 'object'
? JSON.stringify(val, null, 2)
: String(val)
}
7.首字符大写
const capitalize = str => {
return str.charAt(0).toUpperCase() + str.slice(1)
}
8.驼峰转连字符
const hyphenateRE = /\B([A-Z])/g
const hyphenate = str => {
return str.replace(hyphenateRE, '-$1').toLowerCase()
}
9.区分对象和原始值
function isObject (obj) {
return obj !== null && typeof obj === 'object'
}
10.金额千位分割的转换
function fmoney (s, n) {
if (s === 0 || s === '0') {
return 0
}
if (s) {
s += ''
} else {
return ''
}
n = n > 0 && n <= 20 ? n : 2
s = parseFloat((s + '')).toFixed(n) + ''
let l = s.split('.')[0].split('').reverse()
let 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 == '00' ? '' : '.' + r)
}
function rmoney (s) {
if (s || s === 0) {
s += ''
return parseFloat(s.replace(/,/g, ''))
} else {
return ''
}
}
11.IE输入框重渲染,光标问题
function setSelection(element) {
const length = element.value.length;
if (element.createTextRange) {
const sel = element.createTextRange();
sel.moveStart('character', length);
sel.collapse();
sel.select();
} else if (
typeof element.selectionStart === 'number' &&
typeof element.selectionEnd === 'number'
) {
element.selectionStart = element.selectionEnd = length;
}
}
12.判断类型
funcion typeOf (obj) {
const toString = Object.prototype.toString
const map = {
'[object Boolean]': 'boolean',
'[object Number]': 'number',
'[object String]': 'string',
'[object Function]': 'function',
'[object Array]': 'array',
'[object Date]': 'date',
'[object RegExp]': 'regExp',
'[object Undefined]': 'undefined',
'[object Null]': 'null',
'[object Object]': 'object'
}
return map[toString.call(obj)]
}
13.深拷贝
function deepCopy (data) {
const t = this.typeOf(data)
let o
if (t === 'array') {
o = []
} else if (t === 'object') {
o = {}
} else {
return data
}
if (t === 'array') {
for (let i = 0; i < data.length; i++) {
o.push(this.deepCopy(data[i]))
}
} else if (t === 'object') {
for (let i in data) {
o[i] = this.deepCopy(data[i])
}
}
return o
}
14.是否为空对象
function isEmptyObject (obj) {
for (var key in obj) {
return false
};
return true
}
15.日期格式化
function formatDate (date, fmt = 'yyyy-MM-dd') {
if (!this.isDate(date)) {
return 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
}
16.判断闰年
function isLeapYear (year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
}
17.获取页面参数
getAllParams (name) {
const result = {}
const href = decodeURIComponent(window.location.href)
const index = href.indexOf('?')
if (index >= 0 && index + 1 < href.length) { // 存在?且后面还有参数
const paramString = href.split('').slice(index + 1).join('')
paramString.replace(/\?/g, '&').split('&').forEach(item => {
if (item.includes('=')) {
const key = item.split('=')[0]
const value = decodeURIComponent(item.split('=')[1])
result[key] = value
}
})
}
if (name) {
return params[name] || ''
}
return result
}
18.金额千分位(兼容小数)
function fmoney (s, n) {
if (s === 0 || s === '0') {
return 0
}
if (s) {
s += ''
} else {
return ''
}
n = n > 0 && n <= 20 ? n : 2
s = parseFloat((s + '')).toFixed(n) + ''
let l = s.split('.')[0].split('').reverse()
let 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 ? ',' : '')
}
let fix = (r == '00' ? '' : '.' + r)
let result = t.split('').reverse().join('') + fix
if (fix && result.endsWith('0')) {
return result.substring(0, result.length - 1)
}
return result
}
19.判断系统
function os () {
var UserAgent = navigator.userAgent.toLowerCase()
if (/ipad/.test(UserAgent)) return 'ipad'
if (/iphone os/.test(UserAgent)) return 'iphone os'
if (/android/.test(UserAgent)) return 'android'
if (/windows ce/.test(UserAgent)) return 'windows ce'
if (/windows mobile/.test(UserAgent)) return 'windows mobile'
if (/windows nt 5.0/.test(UserAgent)) return 'Win2K'
if (/windows nt 5.1/.test(UserAgent)) return 'windowsXP'
if (/windows nt 6.0/.test(UserAgent)) return 'windowsVista'
if (/windows nt 6.1/.test(UserAgent)) return 'windows7'
if (/windows nt 6.2/.test(UserAgent)) return 'windows8'
if (/windows nt 6.3/.test(UserAgent)) return 'windows81'
if (/mac os/.test(UserAgent)) return 'mac'
}
20.日期处理
const dateFormat = (date, fmt) => {
// author: meizz
let 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 (let 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
}
// 显示当前日期
const dateShow = (date, type) => {
let time = new Date(date),
now = new Date()
if (time * 1 > now * 1) {
return dateFormat(time, 'yyyy-MM-dd')
}
let [year0, month0, day0, hour0] = [
now.getFullYear(),
now.getMonth() + 1,
now.getDate(),
now.getHours()
],
[year1, month1, day1, hour1] = [
time.getFullYear(),
time.getMonth() + 1,
time.getDate(),
time.getHours()
]
if (year0 == year1 && month0 == month1 && day0 !== day1) {
return `${now.getDate() - time.getDate()}天前`
}
if (type !== 'fromPostion') {
if (year0 == year1 && month0 == month1 && day0 == day1 && hour0 == hour1) {
return '刚刚'
}
if (year0 == year1 && month0 == month1 && day0 == day1 && hour0 !== hour1) {
return `${hour0 - hour1}小时前`
}
}
if (type === 'monthDesc') {
const diff = now.getMonth() + 1 - parseInt(dateFormat(time, 'MM'))
if (diff > 12) {
return `${Math.floor(diff / 12)}年前`
} else {
return `${diff}个月前`
}
} else if (type === '') {
if (year0 == year1 && month0 == month1 && day0 == day1) {
return '今天'
}
if (year0 == year1 && month0 == month1 && day0 - day1 == 1) {
return '昨天'
}
}
return dateFormat(time, 'yyyy-MM-dd')
}
// 今天,昨天,XX天前,日期
const transferDate = (date) => {
const DATES = date && date.split(' ')[0]
const timeArr = DATES.split('-')
let now = new Date()
let [year0, month0, day0] = [
now.getFullYear(),
now.getMonth() + 1,
now.getDate()
], [year1, month1, day1] = [
timeArr && parseInt(timeArr[0]),
timeArr && parseInt(timeArr[1]),
timeArr && parseInt(timeArr[2])
]
if (year0 == year1 && month0 == month1 && day0 == day1) {
return '今天'
} else if (year0 == year1 && month0 == month1 && day1 - day0 == -1) {
return '昨天'
} else if (year0 == year1 && month0 == month1 && day0 - day1 >= 2 && day1 - day0 <= 30) {
return `${day1 - day0}天前`
} else {
return `${year1}-${month1}-${day1}`
}
}
21.排序
const sortBy = (target, propertys) => {
if (target == null | target == undefined | target == '') {
return target
} else {
if (propertys.length === 1) {
target = target.sort(by(propertys[0])).reverse()
} else {
target = target.sort(by(propertys[0], by(propertys[1]))).reverse()
}
return target
}
}
const by = (name, minor) => {
return (obj, prot) => {
let a, b
if (obj && prot && typeof obj === 'object' && typeof prot === 'object') {
a = obj[name]
b = prot[name]
if (a === b) {
return typeof minor === 'function' ? minor(obj, prot) : 0
}
if (typeof a === typeof b) {
return a < b ? -1 : 1
}
return typeof a < typeof b ? -1 : 1
} else {}
}
}
22.生成随机数
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
23.防抖函数
const debounce = (func, delay) => {
let timer;
return function (...args) {
if(timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
func.apply(this, args);
clearTimeout(timer);
}, delay);
};
};
24.校验邮箱地址
const validateEmail = (email) => {
if (/^([a-zA-Z0-9_\.\-]+[_|\_|\.]?)*[a-zA-Z0-9_\.\-]+@([a-zA-Z0-9_\.\-]+[_|\_|\.]?)*[a-zA-Z0-9_\.\-]+\.[a-zA-Z]{2,3}$/.test(email)) {
return true
}
return false
}
25.校验身份证号码
// 简单校验
validateIDCard(val) {
const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
return reg.test(val);
},
// 严格校验
const validateIDCard = (idcode) => {
// 加权因子
const weightFactor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
// 校验码
const checkCode = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
const code = `${idcode}`
const last = idcode[17] // 最后一个
const seventeen = code.substring(0, 17)
// ISO 7064:1983.MOD 11-2
// 判断最后一位校验码是否正确
const arr = seventeen.split('')
const len = arr.length
let num = 0
for (let i = 0; i < len; i++) {
num += arr[i] * weightFactor[i]
}
// 获取余数
const resisue = num % 11
const lastNo = checkCode[resisue]
// 格式的正则
// 正则思路
/*
第一位不可能是0
第二位到第六位可以是0-9
第七位到第十位是年份,所以七八位为19或者20
十一位和十二位是月份,这两位是01-12之间的数值
十三位和十四位是日期,是从01-31之间的数值
十五,十六,十七都是数字0-9
十八位可能是数字0-9,也可能是X
*/
// eslint-disable-next-line
const idcardPatter = /^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/
// 判断格式是否正确
const format = idcardPatter.test(idcode)
// 返回验证结果,校验码和格式同时正确才算是合法的身份证号码
return !!(last === lastNo && format)
}
26.校验手机号
const validatePhoneNum = (num) => {
if (/^1[0-9]{10}$/.test(num)) {
return true
}
return false
}
27.获取cookie & 删除cookie
const getCookie = (name) => {
let reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
let arr = document.cookie.match(reg)
if (arr) {
return unescape(arr[2])
} else { return null }
}
const delCookie = (name) => {
let exp = new Date()
exp.setTime(exp.getTime() - 1)
var cval = getCookie(name)
if (cval != null) { document.cookie = name + '=' + cval + ';expires=' + exp.toGMTString() }
}
28.是否微信客户端
const isWxClient = () => {
let microMessenger = window.navigator.userAgent.match(/MicroMessenger/i) || []
return microMessenger[0] === 'MicroMessenger'
}
29.手机客户端类型
const clientMobile = () => {
const obj = {
ios: false,
android: false
}
var ua = navigator.userAgent.toLowerCase()
if (
(ua.match(/iPhone/i) && ua.match(/iPhone/i)[0] === 'iphone') ||
(ua.match(/iPad/i) && ua.match(/iPad/i)[0] === 'ipad')
) {
obj.ios = true
}
if (ua.match(/android/i) && ua.match(/android/i)[0] === 'android') {
obj.android = true
}
return obj
}
30.转义html
const escapeHTML = (str) => {
return str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/\//g, '/')
}
31.localStorage
// 保存缓存数据
const saveStorage = (name, data) => {
try {
localStorage.setItem(`projectName-${name}`, JSON.stringify(data))
} catch (error) { }
}
// 获取缓存数据
const getStorage = (name) => {
try {
let data = localStorage.getItem(`projectName-${name}`)
return data && JSON.parse(data)
} catch (error) { }
}
// 清除缓存数据
const removeStorage = (name) => {
try {
localStorage.removeItem(`projectName-${name}`)
} catch (error) { }
}
32.图片旋转
const rotateImg = (img, direction, canvas) => {
// 最小与最大旋转方向,图片旋转4次后回到原方向
const minStep = 0
const maxStep = 3
if (img == null) return
// img的高度和宽度不能在img元素隐藏后获取,否则会出错
let height = img.height
let width = img.width
let step = 2
if (direction === 'right') {
step++
// 旋转到原位置,即超过最大值
step > maxStep && (step = minStep)
} else {
step--
step < minStep && (step = maxStep)
}
// 旋转角度以弧度值为参数
let degree = step * 90 * Math.PI / 180
let ctx = canvas.getContext('2d')
switch (step) {
case 0:
canvas.width = width
canvas.height = height
ctx.drawImage(img, 0, 0)
break
case 1:
canvas.width = height
canvas.height = width
ctx.rotate(degree)
ctx.drawImage(img, 0, -height)
break
case 2:
canvas.width = width
canvas.height = height
ctx.rotate(degree)
ctx.drawImage(img, -width, -height)
break
case 3:
canvas.width = height
canvas.height = width
ctx.rotate(degree)
ctx.drawImage(img, -width, 0)
break
}
}
33.图片压缩并矫正方向
// Orientation: 图片的元数据
const compress = (img, Orientation) => {
let canvas = document.createElement('canvas')
let ctx = canvas.getContext('2d')
// 瓦片canvas
let tCanvas = document.createElement('canvas')
let tctx = tCanvas.getContext('2d')
// let initSize = img.src.length
let width = img.width
let height = img.height
// 如果图片大于四百万像素,计算压缩比并将大小压至400万以下
let ratio
if ((ratio = width * height / 4000000) > 1) {
// console.log('大于400万像素')
ratio = Math.sqrt(ratio)
width /= ratio
height /= ratio
} else {
ratio = 1
}
canvas.width = width
canvas.height = height
// 铺底色
ctx.fillStyle = '#fff'
ctx.fillRect(0, 0, canvas.width, canvas.height)
// 如果图片像素大于100万则使用瓦片绘制
let count
if ((count = width * height / 1000000) > 1) {
// console.log('超过100W像素')
count = ~~(Math.sqrt(count) + 1) // 计算要分成多少块瓦片
// 计算每块瓦片的宽和高
let nw = ~~(width / count)
let nh = ~~(height / count)
tCanvas.width = nw
tCanvas.height = nh
for (let i = 0; i < count; i++) {
for (let j = 0; j < count; j++) {
tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh)
ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh)
}
}
} else {
ctx.drawImage(img, 0, 0, width, height)
}
// 修复ios上传图片的时候 被旋转的问题
if (Orientation !== '' && Orientation !== 1) {
switch (Orientation) {
case 6: // 需要顺时针(向左)90度旋转
rotateImg(img, 'left', canvas)
break
case 8: // 需要逆时针(向右)90度旋转
rotateImg(img, 'right', canvas)
break
case 3: // 需要180度旋转
rotateImg(img, 'right', canvas) // 转两次
rotateImg(img, 'right', canvas)
break
}
}
// 进行最小压缩
let ndata = canvas.toDataURL('image/jpeg', 0.1)
// console.log('压缩前:' + initSize)
// console.log('压缩后:' + ndata.length)
// console.log('压缩率:' + ~~(100 * (initSize - ndata.length) / initSize) + '%')
tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0
return ndata
}
============上传图片举例:==========
/**
import { EXIF } from 'exif-js'
。。。得到图片文件。。。
let file = e.target.files[0];
let Orientation;
// 获取图片元数据
EXIF.getData(file, function(){
Orientation = EXIF.getTag(this, 'Orientation');
});
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e) {
let imageData = new Image();
imageData.src = e.target.result;
imageData.onload = () => {
let newImage = compress(imageData, Orientation) // 压缩
that.localphoto = this.result;
let image = new FormData();
let stringa = newImage.split(",")[1];
image.append("fileName", file.name);
image.append("base64Str", stringa);
。。。执行上传。。。
};
};
*/
34.阿拉伯数字转中文数字
numberToChn(num) {
const chnNumChar = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
const chnUnitSection = ['', '万', '亿', '万亿', '亿亿'];
const chnUnitChar = ['', '十', '百', '千'];
function SectionToChinese(section) {
let strIns = '';
let chnStr = '';
let unitPos = 0;
let zero = true;
while (section > 0) {
const v = section % 10;
if (v === 0) {
if (!zero) {
zero = true;
chnStr = chnNumChar[v] + chnStr;
}
} else {
zero = false;
strIns = chnNumChar[v];
strIns += chnUnitChar[unitPos];
chnStr = strIns + chnStr;
}
unitPos++;
// eslint-disable-next-line
section = Math.floor(section / 10);
}
return chnStr;
}
let unitPos = 0;
let strIns = '';
let chnStr = '';
let needZero = false;
if (num === 0) {
return chnNumChar[0];
}
while (num > 0) {
const section = num % 10000;
if (needZero) {
chnStr = chnNumChar[0] + chnStr;
}
strIns = SectionToChinese(section);
strIns += (section !== 0) ? chnUnitSection[unitPos] : chnUnitSection[0];
chnStr = strIns + chnStr;
needZero = (section < 1000) && (section > 0);
// eslint-disable-next-line
num = Math.floor(num / 10000);
unitPos++;
}
if (/^一十/.test(chnStr)) {
chnStr = chnStr.substr(1);
}
return chnStr;
}
35.数组去重
getDistinctArray(arr, key) {
const hash = {};
let newArr = [];
if (key) {
newArr = arr && arr.reduce((item, next) => {
hash[next.key] ? '' : hash[next.key] = true && item.push(next);
return item;
}, []);
} else {
newArr = arr && arr.reduce((item, next) => {
hash[next] ? '' : hash[next] = true && item.push(next);
return item;
}, []);
}
return newArr;
}
36.base64 To Blob
base64Img2Blob(base64Data) {
const format = 'image/jpeg';
const base64 = base64Data;
const code = window.atob(base64.split(',')[1]);
const aBuffer = new window.ArrayBuffer(code.length);
const uBuffer = new window.Uint8Array(aBuffer);
for (let i = 0; i < code.length; i++) {
uBuffer[i] = code.charCodeAt(i) & 0xff;
}
let blob = null;
try {
blob = new Blob([uBuffer], {
type: format,
});
} catch (e) {
window.BlobBuilder = window.BlobBuilder ||
window.WebKitBlobBuilder ||
window.MozBlobBuilder ||
window.MSBlobBuilder;
if (e.name === 'TypeError' && window.BlobBuilder) {
const bb = new window.BlobBuilder();
bb.append(uBuffer.buffer);
blob = bb.getBlob('image/jpeg');
} else if (e.name === 'InvalidStateError') {
blob = new Blob([aBuffer], {
type: format,
});
}
}
return blob;
}
37.计算字符串长度,汉子算2个字符
countStringLength(str) {
let valLength = 0;
const chineseReg = /[\u0391-\uFFE5]/;
for (let i = 0; i < str.length; i++) {
let temp = str.substring(i, i + 1);
if (temp.match(chineseReg)) {
valLength += 2;
} else {
valLength += 1;
}
}
return valLength;
}
38.获取图片缩略图
function getThumbImage(url, width = 100, height = 100) {
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
return new Promise((resolve, reject) => {
let image = new Image();
image.onload = () => {
let imgWidth = image.width,
imgHeight = image.height,
startX = 0,
startY = 0;
if (imgWidth > imgHeight && imgHeight > width) {
startX = (imgWidth - imgHeight) / 2;
imgWidth = imgHeight;
} else {
imgWidth = width;
imgHeight = height;
}
context.drawImage(image, startX, startY, imgWidth, imgHeight, 0, 0, width, height);
resolve(canvas.toDataURL());
};
image.src = url;
});
}
39.判断iphoneX
const isiPhoneX = () => {
return (/iphone/gi).test(navigator.userAgent) && ((screen.height == 812 && screen.width == 375) || (screen.height == 896 && screen.width == 414))
}
40.base64转图片
dataURLtoFile(dataurl, filename) {
let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1];
let bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
}
41.删除数组中指定元素
removeArrVal(arr,val){
for(var i=0; i<arr.length; i++) {
if(arr[i] == val) {
arr.splice(i, 1);
break;
}
}
}
42.时间戳转日期
returnStampToDate(timestamp,type){
var date = new Date(timestamp);
var Y = date.getFullYear();
var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1)
var D = (date.getDate()< 10 ? '0'+(date.getDate()) : date.getDate())
const h = date.getHours();
const mm = date.getMinutes();
if(type == 'yyn'){
return Y+''+M+''+D
}
if(type == 'yy'){
return +Y+'.'+M
}
if(type == 'bir'){
return +Y+'.'+M+'.'+D
}
if(type == 'yynt'){
return +Y+'-'+M+'-'+D+' '+h+':'+mm
}
}
43.将文本域中的内容转换成html格式
txtToHtml(txt) {
if (!txt) {
return '';
}
let txtVal = '';
txtVal = txt.replace(/ /g, ' ');
txtVal = txtVal.replace(/\r\n/g, '<br />');
txtVal = txtVal.replace(/\n/g, '<br />');
return txtVal;
}
44.移除class & 增加class
removeClass(ele, cls) {
let eleClass = `${ele.className}`;
eleClass = eleClass.replace(/(\s+)/gi, ' ');
let removed = eleClass.replace(`${cls}`, ' ');
removed = removed.replace(/(^\s+)|(\s+$)/g, '');
ele.className = removed;
},
addClass(ele, cls) {
const eleClass = ele.className;
const blank = (eleClass !== '') ? ' ' : '';
const added = eleClass + blank + cls;
ele.className = added;
}
45.关闭网页 兼容非弹出页面
closeWin() {
if (navigator.userAgent.indexOf('Firefox') !== -1 || navigator.userAgent.indexOf('Chrome') !== -1) {
window.location.href = 'about:blank';
window.close();
} else {
window.opener = null;
window.open('', '_self');
window.close();
}
}