function shuffle(arr){
var len = arr.length;
for(var i = 0; i < len - 1; i++){
var idx = Math.floor(Math.random() * (len - i));
var temp = arr[idx];
arr[idx] = arr[len - i - 1];
arr[len - i -1] = temp;
}
return arr;
}
function randomFrom(lowerValue,upperValue)
{
return Math.floor(Math.random() * (upperValue - lowerValue + 1) + lowerValue);
}
- 获取浏览器类型和版本
```
/**
*
* @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'
}
- 判断`obj`是否为空
```
/**
*
* @desc 判断`obj`是否为空
* @param {Object} obj
* @return {Boolean}
*
* ps: 在 es6中, 使用Object.kes(obj).length
*/
function isEmptyObject(obj) {
if (!obj || typeof obj !== 'object' || Array.isArray(obj))
return false
return !Object.keys(obj).length
}
- 生成指定范围随机数
```
/**
*
* @desc 生成指定范围随机数
* @param {Number} min
* @param {Number} max
* @return {Number}
*/
function randomNum(min, max) {
return Math.floor(min + Math.random() * (max - min));
}
/**
*
* @desc 判断是否为邮箱地址
* @param {String} str
* @return {Boolean}
*/
function isEmail(str) {
return /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(str);
}
/**
*
* @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)
}
/**
*
* @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)
}
/*
@desc 判断是否是手机号与固话
@param {number}
@return {boolean}
*/
function isTel (val) {
var phoneTest = /(^1[3|4|5|6|7|8|9][0-9]{9}$)/
var phoneTest2 = /0\d{2,3}-*\d{7,8}/
if (!phoneTest.test(val) && !phoneTest2.test(val)) {
return false
}
return true
}
/**
*
* @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);
}
/**
*
* @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(/^整$/, '零元整');
}
/**
*
* @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, '":"') + '"}')
}
/**
* @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} 新的节流函数
*/
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;
}
/**
* @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) {
var throttle = this.throttle ? this.throttle : null;
if (!throttle) throw "throttle is no require";
return callback === undefined ? throttle(delay, atBegin, false) : throttle(delay, callback, atBegin !== false);
}
//dom 转 string;
function nodeToString(node){
var temNode = document.createElement("div");
temNode.appendChild( node.cloneNode(true) );
var str = temNode.innerHTML;
temNode = node = null;
return str;
}
/*
@desc dom 转换成html
@params{Element, Object}
@return {String}
*/
function replaceHTML(node, data){
var nodeToString = this.nodeToString ? nodeToString : null;
if (!nodeToString) throw "nodeToString is not require";
var html = "";
var index = 0;
var matcher = /\{\{([\s\S]+?)\}\}|$/g; //匹配{{}} ps: 正则不可以加空格; 会当做特殊字符;
var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;//匹配特殊字符; /n/r...;
var excapes = { //替换匹配的字符;
"'": "'",
"\\": "\\",
"\r": "r",
"\n": "n",
"\t": "t",
"\u2028": "u2028",
"\u2029": "u2029"
}
//将dom转字符串;
html = nodeToString( node );
//定义一个function_main 的字符串函数;
var function_main = "var dataHTML = '';"; //定义一个dataHTML变量保存字符串;
function_main +="dataHTML += '"; //给dataHTML 拼接字符串;
//replace 中回调函数的参数解释;
// * @param match:匹配结果
// * @param $1:第1个()提取结果
// * @param $2:第2个()提取结果
// * @param offset:匹配开始位置
// * @param source:原始字符串
//
// //首先替换掉花括里面的内容;
html.replace( matcher, function(match, $1, offset, source ){
//替换特殊字符;
function_main += html.slice(index. offset).replace(escaper, function(match){
return excapes[match];$1
})
//如果匹配结果, 则将结果加入html内;
if($1){
function_main += "';"+$1+"dataHTML += '";
}
index= offset += match.length; //叠加位置的索引;
return match;
} )
function_main +="'; return dataHTML";
//将数据参入里面, 并将字符串转成可运行的js;
var render = new Function("obj", function_main);
return render(data)
}
/* 发布订阅 */
function veventTrigger() {
var Event = (function() {
var global = this,
Event,
_default = 'default';
Event = function(){
var _listen,
_trigger,
_remove,
_slice = Array.prototype.slice,
_shift = Array.prototype.shift,
_unshift = Array.prototype.unshift,
namespaceCache = {},
_create,
find,
each = function( ary, fn ){
var ret;
for ( var i = 0, l = ary.length; i < l; i++ ){
var n = ary[i];
ret = fn.call( n, i, n);
}
return ret;
};
/*监听事件*/
_listen = function( key, fn, cache ){
if ( !cache[ key ] ){ //不存在的创建
cache[ key ] = [];
}
cache[key].push( fn ); // 添加到事件订阅组;
};
_remove = function( key, cache ,fn){
if ( cache[ key ] ){
if( fn ){ //移除指定函数
for( var i = cache[ key ].length; i >= 0; i-- ){
if( cache[ key ][i] === fn ){
cache[ key ].splice( i, 1 );
}
}
}else{ //移除所有;
cache[ key ] = [];
}
}
};
_trigger = function(){
var cache = _shift.call(arguments), //内部缓存(创建明目空间时加入的)
key = _shift.call(arguments), //key
args = arguments,
_self = this,
ret,
stack = cache[ key ];
if ( !stack || !stack.length ){
return;
}
return each( stack, function(){ //遍历订阅的函数并 发布;
return this.apply( _self, args );
});
};
_create = function( namespace ){
var namespace = namespace || _default;
var cache = {},
offlineStack = [], // 离线事件
ret = {
//发布
listen: function( key, fn, last ){
_listen( key, fn, cache );
if ( offlineStack === null ){
return;
}
if ( last === 'last' ){ //倒序执行;
offlineStack.length && offlineStack.pop()(); //删除并返回最后一个,然后调用这个删除的;
}else{
each( offlineStack, function(){ //顺序执行;
this();
});
}
offlineStack = null; //执行完毕, 清除离线;
},
//
one: function( key, fn, last ){
_remove( key, cache );
this.listen( key, fn ,last );
},
// 移除
remove: function( key, fn ){
_remove( key, cache ,fn);
},
//订阅
trigger: function(){
var fn,
args,
_self = this;
_unshift.call( arguments, cache );
args = arguments;
fn = function(){
return _trigger.apply( _self, args );
};
if ( offlineStack ){
return offlineStack.push( fn );
}
return fn();
}
};
return namespace ?
( namespaceCache[ namespace ] ? namespaceCache[ namespace ] :
namespaceCache[ namespace ] = ret )
: ret;
};
return {
create: _create,
one: function( key,fn, last ){
var event = this.create( );
event.one( key,fn,last );
},
remove: function( key,fn ){
var event = this.create( );
event.remove( key,fn );
},
listen: function( key, fn, last ){
var event = this.create( );
event.listen( key, fn, last );
},
trigger: function(){
var event = this.create( );
event.trigger.apply( this, arguments );
}
};
}();
return Event;
}).call(this);
return Event;
/*
// 先发布后订阅
Event.trigger( 'click', 1 );
Event.listen( 'click', function( a ){
console.log( a ); // 输出:1
});
Event.remove( 'squareMeter88', fn1 ); // 删除小明的订阅
// 使用命名空间
Event.create( 'namespace1' ).listen( 'click', function( a ){
console.log( a ); // 输出:1
});
Event.create( 'namespace1' ).trigger( 'click', 1 );
Event.create( 'namespace2' ).listen( 'click', function( a ){
console.log( a ); // 输出:2
});
Event.create( 'namespace2' ).trigger( 'click', 2 );
*/
}
/*是否是微信*/
function isWeixin() {
var ua = navigator.userAgent.toLowerCase();
if (ua.match(/MicroMessenger/i) == "micromessenger") {
return true;
} else {
return false;
}
}
/*
用 AOP 装饰函数
功能: 在指定函数之前调用函数;
*/
function beforeFn() {
Function.prototype.before = function( beforefn ){
if( typeof beforefn != "function") throw "arguments[0] is not function";
var __self = this; // 保存原函数的引用
return function(){ // 返回包含了原函数和新函数的"代理"函数
beforefn.apply( this, arguments ); // 执行新函数,且保证 this 不被劫持,新函数接受的参数
// 也会被原封不动地传入原函数,新函数在原函数之前执行
return __self.apply( this, arguments ); // 执行原函数并返回原函数的执行结果,
// 并且保证 this 不被劫持
}
}
/*调用视例
var ajax= function( type, url, param ){
console.log(param); // 发送 ajax 请求的代码略
};
var getToken = function(){
return 'Token';
}
ajax = ajax.before(function( type, url, param ){
param.Token = getToken();
});
ajax( 'get', 'http:// xxx.com/userinfo', { name: 'sven' } );
*/
}
/*
用 AOP 装饰函数
功能: 在指定函数之后调用函数;
*/
function afterFn() {
Function.prototype.after = function( afterfn ){
if( typeof afterfn != "function") throw "arguments[0] is not function";
var __self = this;
return function(){
var ret = __self.apply( this, arguments );
afterfn.apply( this, arguments );
return ret;
}
};
/* 使用方法
Function.prototype.before = function( beforefn ){
var __self = this;
return function(){
beforefn.apply( this, arguments );
return __self.apply( this, arguments );
}
}
document.getElementById = document.getElementById.before(function(){
alert (1);
});
var button = document.getElementById( 'button' );
console.log( button );
*/
}
// 加载canvas;
function loadCanvas(options, callback){
var coreCvs = document.createElement('canvas');
var coreCtx = coreCvs.getContext('2d');
var coreImg = new Image();
var returnObj = {};
var coreOptions = options;
coreImg.src = coreOptions.src;
coreImg.onload = function () {
var x = 1; //在背景图中的x (小数(百分比的小数))
var y = 1; // 在背景图中的y (小数(百分比的小数));
var imgData = ''; // 保存二维码图片;
var imgScale = 1; //宽高比例;
imgScale = typeof (this.width / this.height) === 'number' ? (this.width / this.height) : 1;
coreOptions.initial = {};
coreOptions.initial.width = this.width;
coreOptions.initial.height = this.height;
returnObj = setCanvasRize.call(this, coreCvs, coreOptions, imgScale );
callback && callback(returnObj);
}
function setCanvasRize(coreCvs, coreOptions = { width: 0, height: 0}, imgScale) {
coreCvs.width = coreOptions.width;
coreCvs.height = coreOptions.height ? coreOptions.height : (typeof (coreOptions.width / imgScale) === 'number' ? (coreOptions.width / imgScale) : coreOptions.height)
coreCtx.drawImage(this, coreOptions.x || 0, coreOptions.y || 0, coreCvs.width, coreCvs.height);
return {
cvs: coreCvs,
ctx: coreCtx,
coreOptions: coreOptions,
imgScale: imgScale
};
}
}
/*--------------------------- url start ---------------------------*/
/*--------------------------- url end ---------------------------*/
/*--------------------------- Array start ---------------------------*/
/**
*
* 从数组中移除 falsey 值。
使用Array.filter()筛选出 falsey 值 (false、null、0、""、undefined和NaN).
*/
/
const compact = (arr) => arr.filter(Boolean);
// compact([0, 1, false, 2, '', 3, 'a', 'e'*23, NaN, 's', 34]) -> [ 1, 2, 3, 'a', 's', 34 ]
/*
* @desc 深拼合数组。
*
* */
const deepFlatten = arr => [].concat(...arr.map(v => Array.isArray(v) ? deepFlatten(v) : v));
// deepFlatten([1,[2],[[3],4],5]) -> [1,2,3,4,5]
/*
* @desc 去重
*
* */
const distinctValuesOfArray = arr => [...new Set(arr)];
// distinctValuesOfArray([1,2,2,3,4,4,5]) -> [1,2,3,4,5]
/*--------------------------- Array end ---------------------------*/
/*--------------------------- 浏览器 start ---------------------------*/
/*
@desc 如果页的底部可见, 则返回true, 否则为false。
*/
const bottomVisible = () =>
document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight || document.documentElement.clientHeight;
// bottomVisible() -> true
/*
* @desc 返回当前 URL。
* */
const currentURL = () => window.location.href;
// currentUrl() -> 'https://google.com'
/**
*
* @desc 返回当前页的滚动位置。
*
*/
const getScrollPosition = (el = window) =>
({x: (el.pageXOffset !== undefined) ? el.pageXOffset : el.scrollLeft,
y: (el.pageYOffset !== undefined) ? el.pageYOffset : el.scrollTop});
// getScrollPosition() -> {x: 0, y: 200}
/**
*
* @desc 获取滚动条距顶部的距离
*/
function getScrollTop() {
return (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
}
/**
*
* @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;
}
var requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
/**
*
* @desc 在${duration}时间内,滚动条平滑滚动到${to}指定位置
* @param {Number} to
* @param {Number} duration
*/
function scrollTo(to, duration) {
var setScrollTop = this.setScrollTop ? this.setScrollTop : null;
var getScrollTop = this.getScrollTop ? this.getScrollTop : null;
var requestAnimationFrame = this.requestAnimationFrame ? this.requestAnimationFrame : null;
if (!setScrollTop) throw "setScrollTop is no require";
if (!getScrollTop) throw "getScrollTop is no require";
if (!requestAnimationFrame) throw "requestAnimationFrame is no require";
if (duration < 0) {
setScrollTop(to);
return
}
var diff = to - getScrollTop();
if (diff === 0) return
var step = diff / duration * 10;
requestAnimationFrame(
function () {
if (Math.abs(step) > Math.abs(diff)) {
setScrollTop(getScrollTop() + diff);
return;
}
setScrollTop(getScrollTop() + step);
if (diff > 0 && getScrollTop() >= to || diff < 0 && getScrollTop() <= to) {
return;
}
scrollTo(to, duration - 16);
});
}
/**
*
* @desc 设置滚动条距顶部的距离
*/
function setScrollTop(value) {
window.scrollTo(0, value);
return value;
}
/**
*
* @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('&');
}
/*
* @desc 平滑滚动到页面顶部。
*
* */
const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
};
// scrollToTop()
/*
* @ desc 返回两位小数, 并不进行四舍五入
* */
const toFloorFix = num => (Math.floor(num*100)/100).toFixed(2)
/*
* @ desc 转义要在正则表达式中使用的字符串。
* */
const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// escapeRegExp('(test)') -> \\(test\\)
/*
* @ desc 驼峰转换
* */
const fromCamelCase = (str, separator = '_') =>
str.replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2')
.replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2').toLowerCase();
// fromCamelCase('someDatabaseFieldName', ' ') -> 'some database field name'
// fromCamelCase('someLabelThatNeedsToBeCamelized', '-') -> 'some-label-that-needs-to-be-camelized'
// fromCamelCase('someJavascriptProperty', '_') -> 'some_javascript_property'
/*
* @ desc 转驼峰
* */
const toCamelCase = str =>
str.replace(/^([A-Z])|[\s-_]+(\w)/g, (match, p1, p2, offset) => p2 ? p2.toUpperCase() : p1.toLowerCase());
// toCamelCase("some_database_field_name") -> 'someDatabaseFieldName'
// toCamelCase("Some label that needs to be camelized") -> 'someLabelThatNeedsToBeCamelized'
// toCamelCase("some-javascript-property") -> 'someJavascriptProperty'
// toCamelCase("some-mixed_string with spaces_underscores-and-hyphens") -> 'someMixedStringWithSpacesUnderscoresAndHyphens'
/*
* @desc 将字符串截断为指定长度, 并以 ... 替换剩余字符。
* */
const truncateString = (str, num) =>
str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;
// truncateString('boomerang', 7) -> 'boom...'
/*--------------------------- 浏览器 end ---------------------------*/
/*
* @desc 获取类型
* */
const getType = v =>
v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
// getType(new Set([1,2,3])) -> "set"
/*
* @desc 将 colorcode 转换为rgb()字符串。
* */
const hexToRgb = hex => {
const extendHex = shortHex =>
'#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(x => x+x).join('');
const extendedHex = hex.slice(hex.startsWith('#') ? 1 : 0).length === 3 ? extendHex(hex) : hex;
return `rgb(${parseInt(extendedHex.slice(1), 16) >> 16}, ${(parseInt(extendedHex.slice(1), 16) & 0x00ff00) >> 8}, ${parseInt(extendedHex.slice(1), 16) & 0x0000ff})`;
}
// hexToRgb('#27ae60') -> 'rgb(39, 174, 96)'
// hexToRgb('#acd') -> 'rgb(170, 204, 221)'
/*
* @desc 将 RGB 组件的值转换为 colorcode。
* */
const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
// RGBToHex(255, 165, 1) -> 'ffa501'
/*
* @desc 测量执行函数所用的时间。
* */
const timeTaken = callback => {
console.time('timeTaken'); const r = callback();
console.timeEnd('timeTaken'); return r;
};
// timeTaken(() => Math.pow(2, 10)) -> 1024
// (logged): timeTaken: 0.02099609375ms
let requestAnimFrame = function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})
function selectFile() {
var input = document.createElement('input')
input.type = 'file'
input.display="none"
document.querySelector('body').appendChild(input)
input.click();
input.addEventListener("change",function () {
var reader = new FileReader()
reader.readAsDataURL(input.files[0]);
// 读文件成功的回调
reader.onload = function(e) {
console.log(e.target.result)
document.querySelector('#immmg').src = e.target.result
};
})
document.querySelector('body').removeChild(input)
}
网友评论