我的函数库

Map (使用下列有关地图的函数,应该先引入地图js)

计算两地之间距离

1
2
3
4
5
6
7
8
9
10
11
12
13
//  <script type="text/javascript" src='http://webapi.amap.com/maps?v=1.4.0&plugin=AMap.Geolocation,AMap.ToolBar,AMap.Geocoder,AMap.PlaceSearch,AMap.Autocomplete,AMap.Driving&key=40ee88bd05807620f5abe26ebdf51a85'></script>
// <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=Q9AkkY0RD8b9xn4ADVQRvbxm7K5ehxa4"></script>

function distance(lat1,lng1,lat2,lng2) {
// console.log(lat2);
// console.log(lng2);
var map = new BMap.Map("#app");
var point1 = new BMap.Point(lng1,lat1);
var point2 = new BMap.Point(lng2,lat2);
var distance = (map.getDistance(point1,point2)/100000).toFixed(2);
// console.log(distance);
return distance
}

以本地为中心显示地图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function map() {
getlocation()
var map = new AMap.Map('allmap', {
resizeEnable: true,
center:[vm.lng,vm.lat],//地图中心点经纬度
zoom:16 //地图显示的缩放级别)
});
var marker = new AMap.Marker({
position: map.getCenter()
});
marker.setMap(map);
marker.setLabel({ //label默认蓝框白底左上角显示,样式className为:amap-marker-label
offset: new AMap.Pixel(20, 20), //修改label相对于maker的位置
});
$(".amap-logo").remove();
$(".amap-copyright").remove();
}

获取当前位置的经纬度信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/*获取经纬度*/
function getlocation(){
var point = new BMap.Point();

var geolocation = new BMap.Geolocation();
geolocation.getCurrentPosition(function(r){
if(this.getStatus() == BMAP_STATUS_SUCCESS){
var mk = new BMap.Marker(r.point);
var lng = r.point.lng;//经度113.158508
var lat = r.point.lat;//纬度23.063316
// console.log(lng+" "+lat)
}
else {
console.log('failed'+this.getStatus());
}
},{enableHighAccuracy: true})

}

Array

判断两个数组是否相等

1
2
3
4
5
6
7
8
function arrayEqual(arr1, arr2) {
if (arr1 === arr2) return true;
if (arr1.length != arr2.length) return false;
for (var i = 0; i < arr1.length; ++i) {
if (arr1[i] !== arr2[i]) return false;
}
return true;
}

Class

为元素添加class

1
2
3
4
5
function addClass(ele, cls) {
if (!hasClass(ele, cls)) {
ele.className += ' ' + cls;
}
}

判断元素是否有某个class

1
2
3
function hasClass(ele, cls) {
return (new RegExp('(\\s|^)' + cls + '(\\s|$)')).test(ele.className);
}

为元素移除class

1
2
3
4
5
6
function removeClass(ele, cls) {
if (hasClass(ele, cls)) {
var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
ele.className = ele.className.replace(reg, ' ');
}
}

Cookie

根据name读取cookie

1
2
3
4
5
6
7
8
9
10
function getCookie(name) {
var arr = document.cookie.replace(/\s/g, "").split(';');
for (var i = 0; i < arr.length; i++) {
var tempArr = arr[i].split('=');
if (tempArr[0] == name) {
return decodeURIComponent(tempArr[1]);
}
}
return '';
}

根据name删除cookie

1
2
3
4
function removeCookie(name) {
// 设置已过期,系统会立刻删除cookie
setCookie(name, '1', -1);
}

设置Cookie

1
2
3
4
5
6
7
8
9
10
11
12
/**
*
* @desc 设置Cookie
* @param {String} name
* @param {String} value
* @param {Number} days
*/
function setCookie(name, value, days) {
var date = new Date();
date.setDate(date.getDate() + days);
document.cookie = name + '=' + value + ';expires=' + date;
}

Device

获取浏览器类型和版本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
*
* @desc 获取浏览器类型和版本
* @return {String}
*/
function getExplore() {
var sys = {},
ua = navigator.userAgent.toLowerCase(),
s;
(s = ua.match(/rv:([\d.]+)\) like gecko/)) ? sys.ie = s[1]:
(s = ua.match(/msie ([\d\.]+)/)) ? sys.ie = s[1] :
(s = ua.match(/edge\/([\d\.]+)/)) ? sys.edge = s[1] :
(s = ua.match(/firefox\/([\d\.]+)/)) ? sys.firefox = s[1] :
(s = ua.match(/(?:opera|opr).([\d\.]+)/)) ? sys.opera = s[1] :
(s = ua.match(/chrome\/([\d\.]+)/)) ? sys.chrome = s[1] :
(s = ua.match(/version\/([\d\.]+).*safari/)) ? sys.safari = s[1] : 0;
// 根据关系进行判断
if (sys.ie) return ('IE: ' + sys.ie)
if (sys.edge) return ('EDGE: ' + sys.edge)
if (sys.firefox) return ('Firefox: ' + sys.firefox)
if (sys.chrome) return ('Chrome: ' + sys.chrome)
if (sys.opera) return ('Opera: ' + sys.opera)
if (sys.safari) return ('Safari: ' + sys.safari)
return 'Unkonwn'
}

获取操作系统类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
*
* @desc 获取操作系统类型
* @return {String}
*/
function getOS() {
var userAgent = 'navigator' in window && 'userAgent' in navigator && navigator.userAgent.toLowerCase() || '';
var vendor = 'navigator' in window && 'vendor' in navigator && navigator.vendor.toLowerCase() || '';
var appVersion = 'navigator' in window && 'appVersion' in navigator && navigator.appVersion.toLowerCase() || '';

if (/mac/i.test(appVersion)) return 'MacOSX'
if (/win/i.test(appVersion)) return 'windows'
if (/linux/i.test(appVersion)) return 'linux'
if (/iphone/i.test(userAgent) || /ipad/i.test(userAgent) || /ipod/i.test(userAgent)) 'ios'
if (/android/i.test(userAgent)) return 'android'
if (/win/i.test(appVersion) && /phone/i.test(userAgent)) return 'windowsPhone'
}

Dom

获取滚动条距顶部的距离

1
2
3
function getScrollTop() {
return (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
}

获取一个元素的距离文档(document)的位置,类似jQ中的offset()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
*
* @desc 获取一个元素的距离文档(document)的位置,类似jQ中的offset()
* @param {HTMLElement} ele
* @returns { {left: number, top: number} }
*/
function offset(ele) {
var pos = {
left: 0,
top: 0
};
while (ele) {
pos.left += ele.offsetLeft;
pos.top += ele.offsetTop;
ele = ele.offsetParent;
};
return pos;
}

设置滚动条距顶部的距离

1
2
3
4
function setScrollTop(value) {
window.scrollTo(0, value);
return value;
}

Function

函数防抖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* @desc 函数防抖
* 与throttle不同的是,debounce保证一个函数在多少毫秒内不再被触发,只会执行一次,
* 要么在第一次调用return的防抖函数时执行,要么在延迟指定毫秒后调用。
* @example 适用场景:如在线编辑的自动存储防抖。
* @param {Number} delay 0或者更大的毫秒数。 对于事件回调,大约100或250毫秒(或更高)的延迟是最有用的。
* @param {Boolean} atBegin 可选,默认为false。
* 如果`atBegin`为false或未传入,回调函数则在第一次调用return的防抖函数后延迟指定毫秒调用。
如果`atBegin`为true,回调函数则在第一次调用return的防抖函数时直接执行
* @param {Function} callback 延迟毫秒后执行的函数。`this`上下文和所有参数都是按原样传递的,
* 执行去抖动功能时,,调用`callback`。
*
* @return {Function} 新的防抖函数。
*/
function debounce(delay, atBegin, callback) {
return callback === undefined ? throttle(delay, atBegin, false) : throttle(delay, callback, atBegin !== false);
};

函数节流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
* @desc 函数节流。
* 适用于限制`resize`和`scroll`等函数的调用频率
*
* @param {Number} delay 0 或者更大的毫秒数。 对于事件回调,大约100或250毫秒(或更高)的延迟是最有用的。
* @param {Boolean} noTrailing 可选,默认为false。
* 如果noTrailing为true,当节流函数被调用,每过`delay`毫秒`callback`也将执行一次。
* 如果noTrailing为false或者未传入,`callback`将在最后一次调用节流函数后再执行一次.
* (延迟`delay`毫秒之后,节流函数没有被调用,内部计数器会复位)
* @param {Function} callback 延迟毫秒后执行的函数。`this`上下文和所有参数都是按原样传递的,
* 执行去节流功能时,调用`callback`。
* @param {Boolean} debounceMode 如果`debounceMode`为true,`clear`在`delay`ms后执行。
* 如果debounceMode是false,`callback`在`delay` ms之后执行。
*
* @return {Function} 新的节流函数
*/
module.exports = function throttle(delay, noTrailing, callback, debounceMode) {

// After wrapper has stopped being called, this timeout ensures that
// `callback` is executed at the proper times in `throttle` and `end`
// debounce modes.
var timeoutID;

// Keep track of the last time `callback` was executed.
var lastExec = 0;

// `noTrailing` defaults to falsy.
if (typeof noTrailing !== 'boolean') {
debounceMode = callback;
callback = noTrailing;
noTrailing = undefined;
}

// The `wrapper` function encapsulates all of the throttling / debouncing
// functionality and when executed will limit the rate at which `callback`
// is executed.
function wrapper() {

var self = this;
var elapsed = Number(new Date()) - lastExec;
var args = arguments;

// Execute `callback` and update the `lastExec` timestamp.
function exec() {
lastExec = Number(new Date());
callback.apply(self, args);
}

// If `debounceMode` is true (at begin) this is used to clear the flag
// to allow future `callback` executions.
function clear() {
timeoutID = undefined;
}

if (debounceMode && !timeoutID) {
// Since `wrapper` is being called for the first time and
// `debounceMode` is true (at begin), execute `callback`.
exec();
}

// Clear any existing timeout.
if (timeoutID) {
clearTimeout(timeoutID);
}

if (debounceMode === undefined && elapsed > delay) {
// In throttle mode, if `delay` time has been exceeded, execute
// `callback`.
exec();

} else if (noTrailing !== true) {
// In trailing throttle mode, since `delay` time has not been
// exceeded, schedule `callback` to execute `delay` ms after most
// recent execution.
//
// If `debounceMode` is true (at begin), schedule `clear` to execute
// after `delay` ms.
//
// If `debounceMode` is false (at end), schedule `callback` to
// execute after `delay` ms.
timeoutID = setTimeout(debounceMode ? clear : exec, debounceMode === undefined ? delay - elapsed : delay);
}

}

// Return the wrapper function.
return wrapper;

};

Keycode

根据keycode获得键名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
var keyCodeMap = {
8: 'Backspace',
9: 'Tab',
13: 'Enter',
16: 'Shift',
17: 'Ctrl',
18: 'Alt',
19: 'Pause',
20: 'Caps Lock',
27: 'Escape',
32: 'Space',
33: 'Page Up',
34: 'Page Down',
35: 'End',
36: 'Home',
37: 'Left',
38: 'Up',
39: 'Right',
40: 'Down',
42: 'Print Screen',
45: 'Insert',
46: 'Delete',

48: '0',
49: '1',
50: '2',
51: '3',
52: '4',
53: '5',
54: '6',
55: '7',
56: '8',
57: '9',

65: 'A',
66: 'B',
67: 'C',
68: 'D',
69: 'E',
70: 'F',
71: 'G',
72: 'H',
73: 'I',
74: 'J',
75: 'K',
76: 'L',
77: 'M',
78: 'N',
79: 'O',
80: 'P',
81: 'Q',
82: 'R',
83: 'S',
84: 'T',
85: 'U',
86: 'V',
87: 'W',
88: 'X',
89: 'Y',
90: 'Z',

91: 'Windows',
93: 'Right Click',

96: 'Numpad 0',
97: 'Numpad 1',
98: 'Numpad 2',
99: 'Numpad 3',
100: 'Numpad 4',
101: 'Numpad 5',
102: 'Numpad 6',
103: 'Numpad 7',
104: 'Numpad 8',
105: 'Numpad 9',
106: 'Numpad *',
107: 'Numpad +',
109: 'Numpad -',
110: 'Numpad .',
111: 'Numpad /',

112: 'F1',
113: 'F2',
114: 'F3',
115: 'F4',
116: 'F5',
117: 'F6',
118: 'F7',
119: 'F8',
120: 'F9',
121: 'F10',
122: 'F11',
123: 'F12',

144: 'Num Lock',
145: 'Scroll Lock',
182: 'My Computer',
183: 'My Calculator',
186: ';',
187: '=',
188: ',',
189: '-',
190: '.',
191: '/',
192: '`',
219: '[',
220: '\\',
221: ']',
222: '\''
};
/**
* @desc 根据keycode获得键名
* @param {Number} keycode
* @return {String}
*/
function getKeyName(keycode) {
if (keyCodeMap[keycode]) {
return keyCodeMap[keycode];
} else {
console.log('Unknow Key(Key Code:' + keycode + ')');
return '';
}
};

Object

深拷贝,支持常见类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* @desc 深拷贝,支持常见类型
* @param {Any} values
*/
function deepClone(values) {
var copy;

// Handle the 3 simple types, and null or undefined
if (null == values || "object" != typeof values) return values;

// Handle Date
if (values instanceof Date) {
copy = new Date();
copy.setTime(values.getTime());
return copy;
}

// Handle Array
if (values instanceof Array) {
copy = [];
for (var i = 0, len = values.length; i < len; i++) {
copy[i] = deepClone(values[i]);
}
return copy;
}

// Handle Object
if (values instanceof Object) {
copy = {};
for (var attr in values) {
if (values.hasOwnProperty(attr)) copy[attr] = deepClone(values[attr]);
}
return copy;
}

throw new Error("Unable to copy values! Its type isn't supported.");
}

判断obj是否为空

1
2
3
4
5
6
7
8
9
10
11
/**
*
* @desc 判断`obj`是否为空
* @param {Object} obj
* @return {Boolean}
*/
function isEmptyObject(obj) {
if (!obj || typeof obj !== 'object' || Array.isArray(obj))
return false
return !Object.keys(obj).length
}

Random

随机生成颜色

1
2
3
4
5
6
7
8
/**
*
* @desc 随机生成颜色
* @return {String}
*/
function randomColor() {
return '#' + ('00000' + (Math.random() * 0x1000000 << 0).toString(16)).slice(-6);
}

生成指定范围随机数

1
2
3
4
5
6
7
8
9
10
/**
*
* @desc 生成指定范围随机数
* @param {Number} min
* @param {Number} max
* @return {Number}
*/
function randomNum(min, max) {
return Math.floor(min + Math.random() * (max - min));
}

Regexp

判断是否为邮箱地址

1
2
3
4
5
6
7
8
9
/**
*
* @desc 判断是否为邮箱地址
* @param {String} str
* @return {Boolean}
*/
function isEmail(str) {
return /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(str);
}

判断是否为身份证号

1
2
3
4
5
6
7
8
9
/**
*
* @desc 判断是否为身份证号
* @param {String|Number} str
* @return {Boolean}
*/
function isIdCard(str) {
return /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/.test(str)
}

判断是否为手机号

1
2
3
4
5
6
7
8
9
/**
*
* @desc 判断是否为手机号
* @param {String|Number} str
* @return {Boolean}
*/
function isPhoneNum(str) {
return /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/.test(str)
}

判断是否为URL地址

1
2
3
4
5
6
7
8
9
/**
*
* @desc 判断是否为URL地址
* @param {String} str
* @return {Boolean}
*/
function isUrl(str) {
return /[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/i.test(str);
}

String

现金额转大写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
*
* @desc 现金额转大写
* @param {Number} n
* @return {String}
*/
function digitUppercase(n) {
var fraction = ['角', '分'];
var digit = [
'零', '壹', '贰', '叁', '肆',
'伍', '陆', '柒', '捌', '玖'
];
var unit = [
['元', '万', '亿'],
['', '拾', '佰', '仟']
];
var head = n < 0 ? '欠' : '';
n = Math.abs(n);
var s = '';
for (var i = 0; i < fraction.length; i++) {
s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
}
s = s || '整';
n = Math.floor(n);
for (var i = 0; i < unit[0].length && n > 0; i++) {
var p = '';
for (var j = 0; j < unit[1].length && n > 0; j++) {
p = digit[n % 10] + unit[1][j] + p;
n = Math.floor(n / 10);
}
s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
}
return head + s.replace(/(零.)*零元/, '元')
.replace(/(零.)+/g, '零')
.replace(/^整$/, '零元整');
};

Time

格式化${startTime}距现在的已过时间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* @desc 格式化${startTime}距现在的已过时间
* @param {Date} startTime
* @return {String}
*/
function formatPassTime(startTime) {
var currentTime = Date.parse(new Date()),
time = currentTime - startTime,
day = parseInt(time / (1000 * 60 * 60 * 24)),
hour = parseInt(time / (1000 * 60 * 60)),
min = parseInt(time / (1000 * 60)),
month = parseInt(day / 30),
year = parseInt(month / 12);
if (year) return year + "年前"
if (month) return month + "个月前"
if (day) return day + "天前"
if (hour) return hour + "小时前"
if (min) return min + "分钟前"
else return '刚刚'
}

格式化现在距${endTime}的剩余时间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
*
* @desc 格式化现在距${endTime}的剩余时间
* @param {Date} endTime
* @return {String}
*/
function formatRemainTime(endTime) {
var startDate = new Date(); //开始时间
var endDate = new Date(endTime); //结束时间
var t = endDate.getTime() - startDate.getTime(); //时间差
var d = 0,
h = 0,
m = 0,
s = 0;
if (t >= 0) {
d = Math.floor(t / 1000 / 3600 / 24);
h = Math.floor(t / 1000 / 60 / 60 % 24);
m = Math.floor(t / 1000 / 60 % 60);
s = Math.floor(t / 1000 % 60);
}
return d + "天 " + h + "小时 " + m + "分钟 " + s + "秒";
}

Url

url参数转对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
*
* @desc url参数转对象
* @param {String} url default: window.location.href
* @return {Object}
*/
function parseQueryString(url) {
url = url == null ? window.location.href : url
var search = url.substring(url.lastIndexOf('?') + 1)
if (!search) {
return {}
}
return JSON.parse('{"' + decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}')
}

对象序列化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
*
* @desc 对象序列化
* @param {Object} obj
* @return {String}
*/
function stringfyQueryString(obj) {
if (!obj) return '';
var pairs = [];

for (var key in obj) {
var value = obj[key];

if (value instanceof Array) {
for (var i = 0; i < value.length; ++i) {
pairs.push(encodeURIComponent(key + '[' + i + ']') + '=' + encodeURIComponent(value[i]));
}
continue;
}

pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
}

return pairs.join('&');
}