欢迎访问我的 个人博客
记录一下在项目中常用的工具函数,随时更新
var utils = {
/**
* 获取路径参数方法 返回参数值
* @name 参数名字
* */
getQueryString: function (name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
// window.location.search 获取url问号后面部分
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]);
return null;
},
/**
* 设置cookie
* @name cookie名
* @value cookie值
* @expiredays 多少天后过期
* */
setCookie: function (name, value, expiredays) {
var exdate = new Date();
if (!expiredays || isNaN(expiredays)) {
expiredays = 1;
}
exdate.setDate(exdate.getDate() + expiredays);
document.cookie = name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
},
/**
* 读取cookie
* @name cookie名
* */
getCookie: function (name) {
var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
if (arr = document.cookie.match(reg))
return unescape(arr[2]);
else
return null;
},
/**
* 删除cookie
* @name cookie名
* */
delCookie: function (name) {
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval;
var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
if (arr = document.cookie.match(reg))
cval = unescape(arr[2]);
else
cval = null;
if (cval != null)
document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
},
/**
* 设置localStorage
* @name 参数名
* @value 参数值 注:只存字符串类型
* */
setLocalStorage: function (name, value) {
if (typeof name !== "string") {
name = JSON.stringify(name);
}
if (typeof value !== "string") {
value = JSON.stringify(value);
}
localStorage.setItem(name, value);
},
/**
* 获取 localStorage
* @name 参数名
* 注:得到的都是string类型
* */
getLocalStorage: function (name) {
if (typeof name !== "string") {
name = JSON.stringify(name);
}
return localStorage.getItem(name);
},
/**
* 删除 localStorage
* @name 参数名
* */
delLocalStorage: function (name) {
if (typeof name !== "string") {
name = JSON.stringify(name);
}
localStorage.removeItem(name);
},
/**
* 清空 localStorage
* @clear() 清空所有localStorage
* */
clearLocalStorage: function () {
localStorage.clear();
},
/**
* 设置 sessionStorage
* @name 参数名
* @value 参数值 注:只存字符串类型
* */
setSessionStorage: function (name, value) {
if (typeof name !== "string") {
name = JSON.stringify(name);
}
if (typeof value !== "string") {
value = JSON.stringify(value);
}
sessionStorage.setItem(name, value);
},
/**
* 获取 sessionStorage
* @name 参数名
* 注:得到的都是string类型
* */
getSessionStorage: function (name) {
if (typeof name !== "string") {
name = JSON.stringify(name);
}
return sessionStorage.getItem(name);
},
/**
* 删除 sessionStorage
* @name 参数名
* */
delSessionStorage: function (name) {
if (typeof name !== "string") {
name = JSON.stringify(name);
}
sessionStorage.removeItem(name);
},
/**
* 清空 sessionStorage
* @clear() 清空所有localStorage
* */
clearSessionStorage: function () {
sessionStorage.clear();
},
/**
* 获取当前时间
* 格式YYYY-MM-DD hh:mm:ss
*/
getNowTime: function () {
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
var strDate = date.getDate();
var hour = date.getHours();
var minute = date.getMinutes();
var second = date.getSeconds();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
if (hour >= 1 && hour <= 9) {
hour = "0" + hour;
}
if (minute >= 0 && minute <= 9) {
minute = "0" + minute;
}
if (second >= 1 && second <= 9) {
second = "0" + second;
}
var currentTime = year + "-" + month + "-" + strDate + " " + hour + ":" + minute + ":" + second;
return currentTime;
},
/**
* 获取当前时间戳 单位ms
* */
getNowTimeStamp: function () {
var timestamp = new Date().getTime() + "";
return timestamp;
},
/**
* 获取当前日期前后几天当天的日期的方法 (年月日)
* @dayCount
* getYMDStr(0):当天 、 getYMDStr(1):后一天、getYMDStr(-1):前一天
* */
getYMDStr: function (dayCount) {
var dd = new Date();
dd.setDate(dd.getDate() + dayCount);//获取dayCount天后的日期
var y = dd.getFullYear();
var m = (dd.getMonth() + 1) < 10 ? "0" + (dd.getMonth() + 1) : (dd.getMonth() + 1);//获取当前月份的日期,不足10补0
var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();//获取当前几号,不足10补0
return y + "-" + m + "-" + d; //返回年月日
},
/**
* 判断是否为IE浏览器
* @ActiveXObject 只有IE浏览器才有此插件
* */
isIE: function () {
var ms_ie = false;
var ua = window.navigator.userAgent;
var old_ie = ua.indexOf('MSIE ');
var new_ie = ua.indexOf('Trident/');
if ((old_ie > -1) || (new_ie > -1)) {
ms_ie = true;
}
return ms_ie;
},
/**
* 判断是否是PC端
* */
isPCBroswer: function () {
return !(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent));
},
/**
* 阻止事件冒泡
* 使用方法: 在事件函数最后调用stopPropagation(e)
* */
stopPropagation: function (e) {
e = e || window.event;
if (e.stopPropagation) { //W3C阻止冒泡方法
e.stopPropagation();
} else {
e.cancelBubble = true; //IE阻止冒泡方法
}
},
/**
* 单一数组去重 → ["",""]
* @array 传入的数组
* */
delRepeat: function (array) {
if (!(array instanceof Array)) {
console.warn("你传入的不是数组类型");
return false;
}
//去重的方法有很多,我选择了这一种
var result = [];
for (var i = 0; i < array.length; i++) {
if (result.indexOf(array[i]) === -1) {
result.push(array[i]);
}
}
return result;
},
/**
* 数组中Json数据去重 → [{},{}]
* @array 传入的数组
* @attrName 属性名,用json数据中的什么属性名判断是否重复
* */
delRepeatJson: function (array, attrName) {
if (!(array instanceof Array)) {
console.warn("你传入的不是数组类型");
return false;
}
var temp = {}; //用于name判断重复
var result = []; //最后的新数组
array.map(function (item, index) {
if (!temp[item[attrName]]) {
result.push(item);
temp[item[attrName]] = true;
}
});
return result;
},
/**
* 压缩图片处理
* @src 需要压缩的图片base64路径
* @width 图片最大宽度 默认1024
* @format 图片格式 默认jpeg
* @quality 图片质量 0-1,默认1
* @success() 成功后的回调 返回压缩后的base64路径
* */
compressedImage: function (params) {
var that = this;
var initParams = {
src: params.src || "",
width: params.width || 1024,
format: params.format || "jpeg",
quality: params.quality || 1,
};
var image = new Image();
image.src = initParams.src;
image.onload = function () {
//获取图片初始宽高
var width = image.width;
var height = image.height;
//判断图片宽度,再按比例设置宽度和高度的值
if (width > Number(initParams.width)) {
width = Number(initParams.width);
height = Math.ceil(Number(initParams.width) * (image.height / image.width));
}
//将图片重新画入canvas中
var canvas = document.getElementById("compressCanvas");
if (!canvas) { //如果没有压缩用的canvas 就创建一个canvas画布
var body = document.body;
canvas = document.createElement("canvas"); //创建canvas标签
canvas.id = "compressCanvas"; //给外层容器添加一个id
canvas.style.position = "fixed";
canvas.style.zIndex = "-1";
canvas.style.opacity = "0";
canvas.style.top = "-100%";
canvas.style.left = "-100%";
body.appendChild(canvas);
}
var context = canvas.getContext("2d");
canvas.width = width;
canvas.height = height;
context.beginPath();
if (initParams.format !== "png") {
context.fillStyle = "#ffffff";
context.fillRect(0, 0, width, height);
context.fill();
context.closePath();
}
context.drawImage(image, 0, 0, width, height);
var replaceSrc = canvas.toDataURL("image/" + initParams.format + "", initParams.quality); //canvas转DataURL(base64格式)
params.success && params.success(replaceSrc);
};
},
/**
* dataURL转File对象
* @dataUrl base64路径地址
* @fileName 自定义文件名字
* */
dataURLtoFile: function (dataURL, fileName) {
var arr = dataURL.split(','), mime = arr[0].match(/:(.*?);/)[1],
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});
},
/**
* dataURL转成Blob对象
* @dataURI base64路径地址
*/
dataURLtoBlob: function (dataURI) {
var arr = dataURI.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type: mime});
},
/**
* 获取范围内的随机数
* @min 最小值
* @max 最大值
* */
getRandomNum: function (min, max) {
return Math.floor(Math.random() * (min - max) + max);
},
/**
* 获取随机颜色
* @opacity 透明度 默认1
* */
getRandomColor: function (opacity) {
if (!opacity || typeof opacity != "number") {
opacity = 1
}
var red = Math.round(Math.random() * 255);
var green = Math.round(Math.random() * 255);
var blue = Math.round(Math.random() * 255);
return "rgba(" + red + "," + green + "," + blue + "," + opacity + ")";
},
};
随时更新