/** * It checks if the target element has overflow content * @param {Element} element - DOM element target * @returns {boolean} true if the target element has overflow content * @example * <div class="box flex" style="widht: 100px;"> * <div style="width: 200px;"> * </div> * hasOverflow(document.querySelector('.box')); * // true */
hasScrollbar 判断元素是否出现了滚动条
/** * It checks if the target element has scrollbar content considering css properties * @param {Element} element DOM target element * @returns {boolean} true if the element has scrollbar * @example * <div class="box flex" style="widht: 100px;overflow: auto;"> * <div style="width: 200px;"> * </div> * hasOverflow(document.querySelector('.box')); * // true */
hasValue 判断一个字符串是否有值
/** * It checks if the string has value * @param {string} value string to be tested * @returns {boolean} true if the value is valid */hasValue(' ')// false
inRange 判断数字是否在两个数字中间
/** * It checkes if the assigned value is within the given range (inclusive) * @param {number} value - value to be tested * @param {number} min min value * @param {number} max max value * @returns {boolean} true if the number is within the range */inRange(1,2,3)// falseinRange(4,3,5)// true
isDate 判断是否为日期格式
/** * It checks if the assigned parameter is a valid date * @param {any} value */isDate(newDate())// true
isArrayEmpty 判断数组是否为空
/** * It checks if the array is empty * @param {any} value array to be tested * @returns {boolean} true if the array is empty */isArrayEmpty([])// true
isArrayEmpty 判断对象是否为空
/** * It checks if the array is empty * @param {any} value array to be tested * @returns {boolean} true if the array is empty */isObjectEmpty({})// true
isImage 判断是否为图片类型(仅判断后缀名,并不能确定为真的图片)
/** * It checks if the given value is an imageF * @param {string} value string to be tested * @returns {boolean} true if the given value is an image */isImage('ad.png')// true
isJSON 判断是否JSON格式
/** * It checks if the given value is an imageF * @param {string} value string to be tested * @returns {boolean} true if the given value is an image */isJSON('a')// false
isMobile 判断设备是否为手机、pad等移动端设备
/** * It checks if the current user agent is mobile * @returns {boolean} true if the user agent is mobile */isMobile()// true或者是false
isElement 判断是否为dom节点
/** * It checks if assigned parameter is an element * @param {any} value object to be tested * @returns {boolean} true if the element is a valid node */<divclass="box flex"style="widht: 100px;"><divstyle="width: 200px;"></div>
isElement(document.querySelector('.box')) // true
isNumber 判断是否数字
/** * It checks if assigned parameter is a number * @param {any} value any to be tested * @returns {boolean} true if the value is a valid number */isNumber(1)// trueisNumber('1')// trueisNumber('ss')// false
isObject 判断是否为对象
/** * Simple object check * @param {any} value object to be tested * @returns {boolean} true if the value is an object but not an array */isObject({})// trueisObject([])// false
isRegex 判断是否为正则表达式
/** * Simple object check * @param {any} value object to be tested * @returns {boolean} true if the value is an object but not an array */isRegex(/^s/)// trueisRegex('ss')// false
isString 判断是否为字符串string
/** * It checks if the assigned parameter is a string * @param {any} value value to be tested * @returns {boolean} true if value is a string */isString('sss')// trueisString(111)// false
isString 判断是否为字符串string
/** * It checks if the assigned parameter is a string * @param {any} value value to be tested * @returns {boolean} true if value is a string */isString('sss')// trueisString(111)// false
isURL 判断是否为合法的url地址
/** * It checks if the assigned value is a valid URL * @param {string} value string to be tested * @returns {boolean} true if the value is a valid URL */isURL('sss')// falseisURL('[sss/ss](https://wenku.baidu.com)')// true
/** * It convertes date to age value * @param {any} value birthday * @returns {number} age */age(newDate('1994-05-24'))// 27
compareTo 判断给定的两个日期是否相等
/** * It checks if the given dates are equal * @param {date} a date * @param {date} b date * @returns {boolean} true if the dates are equal */compareTo(newDate('1994-05-24'),newDate('1994-05-24'))// true
compareDiff 返回两个时间的时间戳之差
/** * @param {Date | number | string} a * @param {Date | number | string} b * @returns {number} */compareDiff(newDate('1999-05-27'),newDate('1999-05-24'))
toDateTime 把一个字符串变为时间格式
/** * It converts a string to a Date Object * @param {string} value string date * @returns {Date} date */toDateTime('09-28')// Sun Dec 31 1899 09:28:00 GMT+0805 (中国标准时间)
/** * It converts ISO date string to Date * @param {string} value utc string * @returns {Date} Date */fromISO('+2022-05-20T07:29:48.210Z')// Fri May 20 2022 19:29:48 GMT+0800 (中国标准时间)
toISO It returns the ISO date
/** * It returns the ISO date (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ) * @param {Date} value * @returns {string} ISO date */toISO(newDate())//'2022-05-20T07:29:48.210Z'
toTimestamp 获取时间戳
/** * It returns the timestamp of the date * @param {Date} value * @returns {number} respective timestamp */toTimestamp(newDate())// 1653032030336
/** * It manually triggers a determined event * @param {Element} element DOM element target * @param {string} element event name to be triggered * @param {boolean} bubbles 是否冒泡 * <div class="box flex"></div> */trigger(document.querySelector('.box'),'click',false);// 表示触发.box 元素click事件,不冒泡
/** * It gets the index of the element * @param {Element} element - DOM element target * @returns {number} index */<divclass="box flex"><divclass="item1"></div><divclass="item2"></div><divclass="item3"></div></div>indexOf(document.querySelector('.item1'))// 0
insertBefore 在目标元素前插入元素
/** * It inserts element before another * @param {Element} element - DOM element target * @param {Element} node - element to be inserted */<divclass="box flex"><divclass="item1"></div><divclass="item2"></div></div>insertBefore(document.querySelector('.item1'),'<div class="item3"></div>')// <div class="box flex">// <div class="item3"></div>// <div class="item1"></div>// <div class="item2"></div>// </div>
insertAfter 在目标元素后插入元素
/** * It inserts element after another * @param {Element} element - DOM element target * @param {Element} node - element to be inserted */<divclass="box flex"><divclass="item1"></div><divclass="item2"></div></div>insertAfter(document.querySelector('.item1'),'<div class="item3"></div>')// <div class="box flex">// <div class="item1"></div>// <div class="item3"></div>// <div class="item2"></div>// </div>
offset 获取元素距离上、左的距离
/** * It returns the absolute position of the element taking the scroll in considerantion * @param {Element} element DOM element target * @returns {object} { top: number, left: number } */<divclass="box flex"></div>insertAfter(document.querySelector('.box'))// { top: number, left: number }
outerHeight 获取元素占的高度
/** * It calculates the outer height of the element * @param {Element} element DOM element target * @returns {number} height of the element (within margin) */<divclass="box flex"style="height: 100px;margin-top: 20px;"></div>outerHeight(document.querySelector('.box'))// 120
getProperty 获取元素指定属性的值
/** * It returns a determined property from the given element * @param {Element} element DOM element target * @param {string} property property name * @returns {string} property value */<divclass="box flex"data-id="s1sss"></div>getProperty(document.querySelector('.box'),'data-id')// s1sss
/** * It checks whether the target element is in viewport * @param {Element} element DOM element target * @returns {boolean} true if the element is in viewport */<divclass="box flex"style="height: 100px;margin-top: 20px;"></div>inViewport(document.querySelector('.box'))// true || false
find 根据给定的元素或其本身遍历查找元素
/** * It walks the tree to find the element based on the given selector or itself * @param {Element} element DOM root element * @param {string} selector DOM selector * @param {boolean} all (default false) * @returns {Element} element that matches the selector and if all is true, it might returns more than one element */<divclass="box flex"><divclass="item1"></div><divclass="item2"></div></div>find(document.querySelector('.box'),'.item1',true)// <div class="item1"></div>// <div class="item2"></div>
closest 找到给定元素的父元素
/** * It moves backwards on the tree throught the parent nodes * @param {Element} element DOM root element * @param {string} selector DOM selector * @returns {Element} if finds an element which matches the selector, otherwise returns null */<divclass="box flex"><divclass="item1"></div><divclass="item2"></div></div>
matches 递归搜索与给定选择器匹配的元素
/** * It searchs for elements that matches the given selector (recursively) * @param {Element} element DOM root element * @param {string} selector DOM selector * @returns {Element} if finds an element which matches the selector, otherwise returns null */
forward 它在树上通过兄弟元素向前移动
/** * It moves forward on the tree throught the sibling elements * @param {Element} element DOM root element * @param {string} selector DOM selector * @returns {Element} if finds an element which matches the selector, otherwise returns null */
backward 它在树上通过兄弟元素向后移动
/** * It moves backward on the tree throught the sibling elements * @param {Element} element DOM root element * @param {string} selector DOM selector * @returns {Element} if finds an element which matches the selector, otherwise returns null */
/** * It checks if the given values are valid and garantizes that min < max * @param {number} min min value * @param {number} max max value * @returns {array} [min, max] */
/** * It adds leading zeros * @param {number} value number to be filled with leading zeros * @param {number} size result length (default 2) * @returns {string} value if the leading zeros */pad(3,3)//'003'
/** * It generates a random value (decimal) between min and max * @param {number} min min value (default MIN_VALUE) * @param {number} max max value (default MAX_VALUE) * @returns {number} random value */randomDecimal(1,5)// 1.4016161022088092
time 将秒转换为天、小时、分钟、秒
/** * It converts seconds to days, hours, minutes, seconds * @param {number} value time to be converted (in seconds) * @returns {any} an object containing the count of days, hours, minutes and seconds or the value itself */time(11111)// {hour: 3, min: 5, sec: 11}
toTimeString 将秒转换时间字符串
/** * It converts seconds to time string (00:00:00) * @param {number} value time to be converted (in seconds) * @returns {string} an object containing the count of days, hours, minutes and seconds as string */toTimeString(1111)// '18:31'
/** * addition, num + num2 + num3, two numbers is required at least * @param {number} * @returns {number} */plus(0.1,0.2)// = 0.3, not 0.30000000000000004
/** * round a number based on ratio * @param {number} * @returns {number} */round(0.105,2)// = 0.11, not 0.1
object 对象相关的方法
createNamespace 创建命名空间
/* Creates a name namespace. * Example: * var taskService = createNamespace(ics, 'services.task'); * taskService will be equal to ics.services.task * first argument (root) must be defined first ************************************************************/
deepMerge 将两个对象,深度合并
/** * Deep merge two objects * @param {object} original original object * @param {object} params object to be merged * @returns {object} merged object */deepMerge({a: 1,b: {x: 2}},{a: 1,b: {y: 2}})// {a: 1, b: {x: 2, y: 2}}
/** * It parses a form to pair-value object * @param {[Object]} form form array * @returns {Object} form oject or {} if there is no values to parse * @example * * parser([['a',1],['b',2]]); * // => { a: 1, b: 2 } */
swap 交换数组中的两个值
/** * It swaps two elements inside an array * @param {object} elements array * @param {number} from index * @param {number} to index * @returns {object} new array */swap([1,2,3,4])// [1, 4, 3, 2]
string 字符串方法
CamelCasetoKebab 驼峰转短横线
CamelCasetoKebab('carId')// car-id
KebabtoCamelCase 短横线转小驼峰
KebabtoCamelCase('car-id')// carId
KebabtoPascalCase 短横线转大驼峰
KebabtoPascalCase('car-id')// CarId
capitalizes 大写首字母
/** * It capitalizes the given string * @param {string} value value to be capitalized * @returns {string} captalized value */capitalizes(car)// Car
toRGB 将hex颜色转为rgb颜色
/** * It converts an Hex color to a RGB color * @param {string} value - Hex color with or without `#` * @return {object?} { r: number, g: number, b: number } or undefined if does not match */toRGB('#4e6ef2')// { r: 78, g: 110, b: 242 }
toHex 将rgb颜色转为hex颜色
/** * It converts an RGB color to an Hex color * @param {string} value RGB color * @param {string} prefix default value '#' * @return {string} Hex color or the entered value */toHex('78,110,242')// #4E6EF2
getContrast 为给定背景确定最合适的文本颜色
/** * It determines the most appropriate text color for the given background * @param {string} value - background color (RGB color string) * @param {string} light color when light (default #fff) * @param {string} dark color when dark (default #000) * @returns {string} the color with the most appropriate contrast */getContrast({r: 78,g: 110,b: 242})//'#fff'
filesize 获取文件大小
/** * It converts filesize from bytes to gigabytes, megabytes, kilobytes and bytes * @param {number} value value to be converted to string * @param {number} base default 1024 * @returns {string} string representation of the filesize */
/* Formats a string just like string.format in C#. * Example: * formatString('Hello {0}','Tuana') = 'Hello Tuana' ************************************************************/
/** * It removes all the accentuation * @param {string} value to be replaced * @returns {string} formatted value */normalize('ÁÀÂÃÄ')// AAAAA
objectId 生成对象的唯一id
/** * It generates ObjectId (mongodb) * @param {Math} math * @param {DateConstructor} date * @param {Function} callback * @returns {string} */objectId()// 628756d34d6d7a5336ffa473
replaceAll 替换字符串
/* Find and replaces a string (search) to another string (replacement) in * given string (str). * Example: * replaceAll('This is a test string', 'is', 'X') = 'ThX X a test string' ************************************************************/
/** * It generates a token with a determined length with only numbers (0-9) * @param {number} len length of the code * @returns {string} generated token */generateCode(5)// '27565'
generateKey 生成一个指定长度的只有数字(不含0)和字母的token
/** * It generates a token with a determined length with only letters and numbers excluding zero * @param {number} len length of the code * @returns {string} generated token */generateKey(5)// 'jYSPJ'
/** * It generates a random and unique value * @returns {string} unique value */uniqueId()// 'fsfoyh57hkw'
getStrokeCode 获取五笔码
/** * @returns {string} value */getStrokeCode('你好')// 'WV'
getFirstSpell getFullSpell 拼音码首拼、全拼
/** * @returns {string} value */getFirstSpell('你好')// 'NH'getFullSpell('你好')// 'nihao'
URLJoin 拼接url
/** * URLJoin * * @param args * @returns {string} * @description * Joins all given URL segments together, then normalizes the resulting URL. Use String.prototype.join('/') to combine URL segments, then a series of String.prototype.replace() calls with various regexps to normalize the resulting URL (remove double slashes, add proper slashes for protocol, remove slashes before parameters, combine parameters with '&' and normalize first parameter delimiter). * @example * * URLJoin('http://www.google.com', 'a', '/b/cd', '?foo=123', '?bar=foo'); * // => 'http://www.google.com/a/b/cd?foo=123&bar=foo' */
雪花算法,生成id
/** * URLJoin * * @param workerId 标识ID * @param dataCenterId 机器ID * @returns {string} * @description * Joins all given URL segments together, then normalizes the resulting URL. Use String.prototype.join('/') to combine URL segments, then a series of String.prototype.replace() calls with various regexps to normalize the resulting URL (remove double slashes, add proper slashes for protocol, remove slashes before parameters, combine parameters with '&' and normalize first parameter delimiter). * @example **/const{ SnowFlake }=stringconstsnowflake=newSnowFlake(1,1,0)snowflake.nextId()
/** * Sets a cookie value for given key. * This is a simple implementation created to be used by ics. * Please use a complete cookie library if you need. * @param {string} key * @param {string} value * @param {Date} expireDate (optional). If not specified the cookie will expire at the end of session. * @param {string} path (optional) */buildQueryString('name','dengliu2',newDate('2024-06-28'),'system')
getCookieValue 获取cookie
/** * Gets a cookie with given key. * This is a simple implementation created to be used by ics. * Please use a complete cookie library if you need. * @param {string} key * @returns {string} Cookie value or null */getCookieValue('name')// 'dengliu2;path=system'