Skip to content

Instantly share code, notes, and snippets.

@lcat
Last active March 17, 2020 02:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lcat/f61a821b7b6ce320c23cdd5e530ffd19 to your computer and use it in GitHub Desktop.
Save lcat/f61a821b7b6ce320c23cdd5e530ffd19 to your computer and use it in GitHub Desktop.
常用工具类函数
let rsAstralRange = '\\ud800-\\udfff',
rsZWJ = '\\u200d',
rsVarRange = '\\ufe0e\\ufe0f',
rsComboMarksRange = '\\u0300-\\u036f',
reComboHalfMarksRange = '\\ufe20-\\ufe2f',
rsComboSymbolsRange = '\\u20d0-\\u20ff',
rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange;
let reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');
let rsFitz = '\\ud83c[\\udffb-\\udfff]',
rsOptVar = '[' + rsVarRange + ']?',
rsCombo = '[' + rsComboRange + ']',
rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
reOptMod = rsModifier + '?',
rsAstral = '[' + rsAstralRange + ']',
rsNonAstral = '[^' + rsAstralRange + ']',
rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
rsSeq = rsOptVar + reOptMod + rsOptJoin,
rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
let reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
function hasUnicode (val) {
return reHasUnicode.test(val);
}
function unicodeToArray (val) {
return val.match(reUnicode) || [];
}
function asciiToArray (val) {
return val.split('');
}
export default {
// 获取缓存值(不兼容localStorage的走cookie)
getCacheItem(key) {
if (window.localStorage) {
return window.localStorage.getItem(key);
} else {
return this.getCookieItem(key);
}
},
// 设置缓存值
setCacheItem(key, value) {
if (window.localStorage) {
window.localStorage.setItem(key, value);
} else {
this.setCookieItem(key, value);
}
return true;
},
// 移除缓存值
removeCacheItem(key) {
if (window.localStorage) {
window.localStorage.removeItem(key);
} else {
this.removeCookieItem(key);
}
return true;
},
// 获取某个cookie值
getCookieItem(key) {
const arrStr = document.cookie.split('; ');
for (let i = 0; i < arrStr.length; i++) {
const temp = arrStr[i].split('=');
if (temp[0] == key) return decodeURIComponent(temp[1]);
}
// no this cookie
return null;
},
// 设置cookie值
setCookieItem(key, value, Days = 30) {
const exp = new Date();
exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
document.cookie = key + '=' + encodeURIComponent(value) + ';expires=' + exp.toGMTString();
},
// 移除某个cookie
removeCookieItem(key) {
const exp = new Date(),
val = this.getCookieItem(key);
exp.setTime(exp.getTime() - 1);
if (val != null) document.cookie = key + '=' + val + ';expires=' + exp.toGMTString();
},
getQuery(name, string = '') {
let url = decodeURIComponent(location.href),
query = location.search.substr(1) || url.split('?')[1] || '',
result = this.parseQuery(string ? string : query)[name];
return result ? result : null;
},
setQuery() {
let result = '',
value = '',
string = '',
object = {};
if (typeof arguments[0] === 'string') {
string = arguments[2];
object = {
[arguments[0]]: arguments[1],
};
} else {
string = arguments[1];
object = arguments[0];
}
for (let name in object) {
if (name === '') return string;
if (!string) string = location.href;
value = object[name];
name = name.replace(/[\[\]]/g, `\\$&`);
const REG = new RegExp(`${name}=[^&]*`);
const [search, hash] = string.split(`#`);
value = `${name}${encodeURIComponent(value) ? '=' + encodeURIComponent(value) : ''}`;
result = REG.exec(string) ? string.replace(REG, value) : `${search}${value ? '&' + value : ''}${hash || ''}`;
}
return result;
},
getHash(name, string = '') {
let url = decodeURIComponent(location.href),
query = location.hash.substr(1) || url.split('#')[1] || '',
result = this.parseQuery(string ? string : query)[name];
return result ? result : null;
},
parseQuery(query) {
let result = {},
param = '',
params = [],
str = decodeURIComponent(query);
if (str) params = str.split('&');
for (let i = 0; i < params.length; i++) {
param = params[i].split('=');
param[0] ? (result[param[0]] = param[1] === undefined ? null : param[1]) : '';
}
return result;
},
// 预加载图片
preload(imageUrls) {
let images = [],
count = 0,
doneAction = function () { },
progressAction = function () { };
imageUrls = (typeof imageUrls != 'object') ? [imageUrls] : imageUrls;
imageUrls.length === 0 && setTimeout(() => doneAction(images), 0);
imageUrls.map((image, i) => {
images[i] = new Image();
images[i].src = image;
images[i].onload = imageLoad;
images[i].onerror = imageLoad;
});
function imageLoad() {
progressAction((count + 1) * 100 / images.length, images[count]);
count++;
if (count == imageUrls.length) doneAction(imageUrls.length === 1 ? images[0] : images);
}
return {
done() {
doneAction = arguments[0] || doneAction;
},
progress() {
progressAction = arguments[0] || progressAction;
},
};
},
// 获取随机数
getRandomNum(Min = 0, Max = 10) {
const Range = Max - Min;
return (Min + Math.round(Math.random() * Range));
},
// ua 判断平台
is() {
let ua = window.navigator.userAgent.toLowerCase();
return {
iOS: /(iPhone|iPad|iPod|iOS)/gi.test(ua),
Android: /android|adr/gi.test(ua),
Mobile: /(iPhone|iPad|iPod|iOS|Android|adr|Windows Phone|SymbianOS)/gi.test(ua),
Weibo: /(weibo)/gi.test(ua),
WeChat: ua.match(/MicroMessenger/gi) == 'micromessenger' ? true : false,
QQ: /qq\//gi.test(ua),
Qzone: ua.indexOf('qzone/') !== -1,
};
},
/**
* zepto window scroll to with animation
* @param to [init] scroll到多少px
* @param duration [init] 持续时间
*/
smoothScroll(to, duration) {
if (duration < 0) {
return;
}
var difference = to - $(window).scrollTop();
var perTick = difference / duration * 10;
var scrollToTimerCache = setTimeout(function () {
if (!isNaN(parseInt(perTick, 10))) {
window.scrollTo(0, $(window).scrollTop() + perTick);
this.smoothScroll(to, duration - 10);
}
}.bind(this), 10);
},
// 位数补全 eg. 2->02 5->005
appendzero(num, size = 2) {
let str = Array(size + 1).join('0') + num;
return str.substr(str.length - size);
},
getYear() {
return new Date().getFullYear();
},
getMonth() {
var month = new Date().getMonth() + 1;
return this.appendzero(month);
},
getDate() {
var date = new Date().getDate();
return this.appendzero(date);
},
guid() {
function S4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
return (S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4());
},
trim(str = '') {
return str.replace(/^\s+|\s+$/g, '');
},
addClass(element, className) {
if (element.classList) {
element.classList.add(className);
} else {
element.className += ` ${className}`;
}
},
removeClass(element, className) {
if (element.classList) {
element.classList.remove(className);
} else {
element.className = element.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
}
},
hasClass(element, className) {
return new RegExp(' ' + className + ' ').test(' ' + element.className + ' ');
},
isEmpty(obj = {}) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
},
getByteLen(val = '') {
var len = 0;
var arr = hasUnicode(val) ? unicodeToArray(val) : asciiToArray(val);
for (var i = 0; i < arr.length; i++) {
var a = arr[i];
if (a.match(/[^\x00-\xff]/gi) != null) {
len += 2;
} else {
len += 1;
}
}
return len;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment