TIP
一些也许会用到的函数
浮点数加法运算
js
function sum(arg1, arg2) {
let 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).toFixed(0) + +(arg2 * m).toFixed(0)) / m;
}
查询元素距离文档顶部和左端的距离
js
function offset(element) {
const pos = { left: 0, top: 0 };
let parents = element.offsetParent;
pos.left += element.offsetLeft;
pos.top += element.offsetTop;
while (parents && !/html|body/i.test(parents.tagName)) {
pos.left += parents.offsetLeft;
pos.top += parents.offsetTop;
parents = parents.offsetParent;
}
return pos;
}
判断是否是移动端浏览器
js
function judgeIsMobileBrowser() {
return /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i.test(navigator.userAgent);
}
查询窗口滚动条位置
js
function getScrollOffsets(w) {
// 可使用指定的窗口
w = w || window;
// 除ie8及更早的版本以外,其他浏览器都可以用
if (w.pageXOffset != null) return { x: w.pageXOffset, y: w.pageYOffset };
// 对标准模式下的IE(或任何浏览器)
var d = w.document;
if (document.compatMode == "CSS1Compat")
return { x: d.documentElement.scrollLeft, y: documentElement.scrollTop };
// 对怪异模式下的浏览器
return { x: d.body.scrollLeft, y: d.body.scrollTop };
}
查询窗口的视口尺寸
js
function getViewportSize(w) {
w = w || window;
// 除ie8及更早的版本以外,其他浏览器都可以用
if (w.innerWidth != null) return { x: w.innerWidth, y: w.innerHeight };
// 对标准模式下的IE(或任何浏览器)
var d = w.document;
if (document.compatMode == "CSS1Compat")
return { x: d.documentElement.clientWidth, y: documentElement.clientHeight };
// 对怪异模式下的浏览器
return { x: d.body.clientWidth, y: d.body.clientHeight };
}
查询选取的文本
js
function getSelectedText() {
if (window.getSelection)
return window.getSelection.toString();
else if (document.selection)
return document.selection.createRange().text;
}
取消默认事件
js
function cancelHandle(event) {
var event = event || window.event; // 用于ie
if (event.preventDefault) event.preventDefault(); // 标准技术
if (event.returnValue) event.returnValue = false; // ie
return false; // 用于处理使用对象属性注册的处理程序
}
jsonp
js
function getJSONP(url, callback) {
// 为本次请求创建一个唯一的回调函数名称
var cbnum = 'cb' + getJSONP.counter++;
var cbname = 'getJSONP.' + cbnum;
// 将回调函数名称添加到url后面
if (url.indexOf('?') === -1) // url没有查询参数
url += '?jsonp=' + cbname;
else
url += '&jsonp=' + cbname;
var script = doucument.createElement('script');
getJSONP[cbnum] = function(response) {
try {
callback(response);
}
finally {
delete getJSONP[cbnum];
script.parentNode.removeChild(script);
}
};
script.src = url;
document.body.appendChild(script);
}
getJSONP.counter = 0;
文件转base64
js
export function fileToBase64(file) {
return new Promise((resolve, reject) => {
const rs = new FileReader();
rs.readAsDataURL(file);
rs.onload = function(e) {
resolve(e.target.result);
};
rs.onerror = function(err) {
reject(err);
};
});
}
blob转base64
同样可以使用“文件转base64”的方法,但是从服务器获取的blob对象,转出来是“text/xml”格式的,所以就另辟蹊径
js
export function imgBlobToBase64(blob) {
const cvs = document.createElement('canvas');
const ctx = cvs.getContext('2d');
const url = URL.createObjectURL(blob);
const img = new Image();
img.src = url;
return new Promise((resolve, reject) => {
img.onload = function() {
ctx.clearRect(0, 0, cvs.width, cvs.height);
cvs.width = img.width;
cvs.height = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
const base64 = cvs.toDataURL('image/png');
resolve(base64);
};
});
}
base64转为二进制
js
function base64UrlToBlob(urlData){
var bytes=window.atob(urlData.split(',')[1]); //去掉url的头,并转换为byte
//处理异常,将ascii码小于0的转换为大于0
var ab = new ArrayBuffer(bytes.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i);
}
return new Blob( [ab] , {type : 'image/jpeg'});
}
base64转file
js
function dataURLtoFile(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});
}
buffer转base64
js
export function bufferToBase64(buffer) {
let binary = '';
const bytes = new Uint8Array(buffer);
const len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}
动态创建a标签下载文件
js
export function aDownload(src, name) {
const a = document.createElement('a');
a.href = src;
a.download = name;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
判断第一个数组是否包含第二个数组
js
export function arrIsFather(arr1, arr2) {
let arr = arr2.join(',').split(',');
if (arr1.length < arr2.length) {
return false;
}
for (let i = 0; i < arr1.length; i++) {
arr = arr.filter(item => {
return item !== arr1[i];
});
}
if (arr.length > 0) {
return false;
} else {
return true;
}
}
解析url参数
js
function getUrlParams(url) {
const reg = /([^?=&]+)=([^?=&]+)/g;
const obj = {};
url.replace(reg, (m, $1, $2) => { obj[$1] = $2; });
return obj;
}
深拷贝
js
function deepClone(obj, cache=new Map()) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
if(obj instanceof Date) {
return new Date(obj);
}
if(obj instanceof RegExp) {
return new RegExp(obj);
}
if(cache.get(obj)) {
return cache.get(obj);
}
let cloneObj = {};
if(Array.isArray(obj)) {
cloneObj = [];
}
cache.set(obj, cloneObj);
for(let key in obj) {
if(obj.hasOwnProperty(key)) {
cloneObj[key] = deepClone(obj[key], cache);
}
}
return cloneObj;
}