这篇贴子会收录个人觉得有用的方法。如果大家也有一些非常不错的封装,那么还请不吝赐教,谢谢。
1.判断浏览环境
#这里还可以添加判断设备如小米,华为,版本等...
function devices(){
let UA = navigator.userAgent,
isAndroid = /android|adr|linux/gi.test(UA),
isIOS = /iphone|ipod|ipad/gi.test(UA) && !isAndroid,
isBlackBerry = /BlackBerry/i.test(UA),
isWindowPhone = /IEMobile/i.test(UA),
isMobile = isAndroid || isIOS || isBlackBerry || isWindowPhone;
return {
isAndroid: isAndroid, //true 安卓,false不是安卓
isIOS: isIOS, //true 苹果,false不是苹果
isMobile: isMobile, //true 移动端, false不是移动端
isWeixin: /MicroMessenger/gi.test(UA), //true 微信,false不是微信
isQQ: / QQ/gi.test(UA), //true QQ ,false不是QQ
isPC: !isMobile //true PC ,false不是PC
};
}
2.浏览器参数与对象之间互相转化
//获取浏览器参数
let param = location.search.substr(1);
/**
* 参数:data type:String eg: 'a=1&b=2'
* 返回:obj type:Object {a=1,b=2}
**/
const strSerializationObj = data =>{
let query = {};
data.split('&').forEach(val =>{
const [key,value] = val.split('=');
if(key) query[key] = value;
});
return query;
}
/**
* 参数:data type:Object eg: {a=1,b=2}
* 返回:str type:String eg: 'a=1&b=2'
**/
const objSerializationStr = data =>{
let str = '';
for (let [k, v] of Object.entries(data)) {
str += `${k}=${v}&`
}
str = str.slice(0,str.length-1);
return str;
}
const cursor = function(){
//获取光标位置
function get (ctrl){
let caretPos = 0; //IE Support
if (document.selection) {
ctrl.focus ();
let sel = document.selection.createRange();
sel.moveStart ('character', -ctrl.value.length);
caretPos = sel.text.length;
// Firefox support
}else if (ctrl.selectionStart || ctrl.selectionStart == '0')
caretPos = ctrl.selectionStart;
return (caretPos);
}
//设置光标位置函数
function set (ctrl,pos){
if(ctrl.setSelectionRange){
ctrl.focus();
ctrl.setSelectionRange(pos,pos);
}else if(ctrl.createTextRange){
let range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
return {
get:get,
set:set
}
}
4.格式化日期
/**
*参数:data type:number 时间戳
*返回:str type:String 2017/12/12 10:12:50
**/
const formatTime = date => {
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hour = date.getHours();
const minute = date.getMinutes();
const second = date.getSeconds();
return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':');
}
const formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n;
}
5.驼峰转换大写
var str = "getParentAreaStruc";
str.replace(/([A-Z])/g,"_$1").toUpperCase();
// GET_PARENT_AREA_STRUC
6.文本保存成文件
function createAndDownloadFile(fileName, content) {
var aTag = document.createElement('a');
var blob = new Blob([content]);
aTag.download = fileName;
aTag.href = URL.createObjectURL(blob);
aTag.click();
URL.revokeObjectURL(blob);
}
createAndDownloadFile('a.txt','测试数据');
7.js模仿seleep函数
//每隔5秒中输出一个数字
var arr = [1,2,3,4,5,6,7,8];
arr.forEach(val=>{
console.log(val);
seleep(5);
})
function seleep(s) {
const time = s * 1000 + Date.parse(new Date());
while (time > Date.parse(new Date())) {
;
}
},
8.保留n位小数
formatFloat = (val, n, toLocaleString) => {
let data = (Math.round(val * 10 ** n) / 10 ** n).toFixed(n)
if (toLocaleString && +data >= 1000) {
const arr = data.split('.')
data = (+arr[0]).toLocaleString() + (arr[1] ? '.' + arr[1] : '')
}
return data
}
formatFloat(0.11231231,3)
9.替换指定的字符串
strReplace = (str, ...params) => {
let i = 0
return str.replace(/\${.*?}/g, () => {
return params[i++] || '${}'
})
}
str = 'Hello, ${How} are ${} you? ${}'
strReplace(str,'**','&&')
//输出
Hello, ** are && you? ${}
10.输入框限制数字
/**
* 表单输入限制只能输入数字时使用
* @param {String} amount
* @param {Numver} toFixed 保留位数
* @param {Numver} max 字符串最长长度
*/
export const validNumber = (amount, toFixed = 8, max = 10) => {
const reg = new RegExp(`^(\\.*)(\\d+)(\\.?)(\\d{0,${toFixed}}).*$`, 'g')
let val = amount
.toString()
.replace(/[^\d|.]|^\.*/g, '')
.replace(reg, '$2$3$4')
if (toFixed === 0) {
val = Math.floor(val).toString()
}
return max && !isNaN(max) ? val.substr(0, max) : val
}
11.svg文件转成dom
将svg文件转成dom
#修改请求文件头信息,将返回的svg文件修改为 text/plain,然后在插入到dom中
const matchDecimalLimit = new RegExp(`^\\d+(\\.\\d{0,${size}})?$`)
if (value && !matchDecimalLimit.test(value)) return
setAmount(value)