- 获取当前元素相对于document 的偏移量
const getOffset = el => {const { top, left } = el.getBoundingClientRect()const { scrollTop, scrollLeft } = document.bodyreturn {top: top + scrollTop,left: left + scrollLeft,}}
- 获取元素类型
const dataType = obj => Object.prototype.toString.call(obj).replace(/^\[object (.+)\]$/, '$1').toLowerCase()
- 判断是否是移动端
const isMobile = () => 'ontouchstart' in window
- 禁止网页复制粘贴
const html = document.querySelector("html")html.oncopy = () => falsehtml.onpaste = () => false
- 去除字符串中的html代码
const removeHTML = (str = "") => str.replace(/<[\/\!]*[^<>]*>/ig, '')console.log(removeHTML("<h1>Hello World</h1>"))
- input 只能输入中文
const input = document.querySelector('input')const clearText = target => {const {value} = targettarget.value = value.replace(/[^\u4e00-\u9fa5]/g, '')}input.onfocus = ({target}) => {clearText(target)}input.onblur = ({target}) => {clearText(target)}input.onkeyup = ({target}) => {clearText(target)}input.oninput = ({target}) => {clearText(target)}
- fade 动画
const fade = (el, type = "in") => {el.style.opacity = (type === 'in') ? 0 : 1let last = +new Date()const tick = () => {const opacityValue = (type === 'in')? (new Date() - last) / 400? -(new Date() - last) / 400el.style.opacity = +el.style.opacity + opacityValuelast = +new Date()if (type === 'in' ? (+el.style.opacity < 1) : (+el.style.opacity > 0)) {requestAnimationFrame(tick)}}tick()}
- 字符串后面空格去除和替换
const trimEnd = str => str.replace(new RegExp('^(.*?)([\\s]*)$'), '$1')console.log(trimEnd("abc")) // abcconsole.log(trimEnd("123")) // 123
- 获取当前子元素是其父元素下子元素的排位
const getIndex = el => {if (!el) return -1let index = 0;do {index++} while(el = el.previousElementSibling) // 返回当前元素在其父元素的子元素节点中的前一个元素节点,如果该元素已经是第一个元素节点,则返回null,该属性是只读的return index;}
- 字符串前面空格去除和替换
const trimStart = str => str.replace(new RegExp('^([\\s]*)(.*?)$'), '$2');console.log(trimStart(" abc ")) // 'abc 'console.log(trimStart("123 ")) // '123 '
- 函数柯里化
const curring = fn => {const {length} = fn;const curried = (...args) => {return args.length >= length? fn(...args): (...args2) => curried(args.concat(args2))}return curried}const listMerge = (a,b,c) => [a, b,c]const curried = curring(listMerge)console.log(curried(1)(2)(3)) // [1,2,3]console.log(curried(1,2,3)) // [1,2,3]console.log(curried(1,2)(3)) // [1,2,3]
- 获取数组交集
const intersection = (list, ...args) => list.fliter(item => args.every(list => list.includes(item)))console.log(intersection([2,1], [2,3])) // [2]console.log(intersection([1,2], [3,4])) // []
- 分割指定的长度的元素数组
const listChunk = (list, size = 1, cacheList = []) => {const temp = [...list]if (size <= 0) {return cacheList}while(temp.length) {cacheList.push(temp.slice(0, size))}return cacheList}console.log(listChunk([1, 2, 3, 4, 5, 6, 7, 8, 9], 3)) // [[1,2,3], [4,5,6,], [7,8,8]]console.log(listChunk([1, 2, 3, 4, 5, 6, 7, 8, 9], 0)) // []
- 延迟函数delay
const delay = ms => new Promise((resolve, reject) => setTimout(resolve, ms))const getData = status => new Promise((resolve, reject) => {status ? reslove('done') : reject('fail')})const getResult = async (data) => {try {const result = await getData(data)const timestamp = new Date().getTimeawait delay(1000)console.log(result, new Date().getTime() - timestamp)}catch(e) {console.log(e)}}getResult(true) // 隔了一秒
- 将指定格式字符串解析为日期字符串
const dataPattern = (str, format = '-') => {if (!str) return new Date()const dateReg = new RegExp('^(\\d{2})${format}(\\d{2})${foramt}(\\d{4})$')const [, month, day, year] = dateReg.exec(dateReg)return new Date(`${month}, ${day} ${year}`)}console.log(datePattern('12-25-1995')) //Mon Dec 25 1995 00:00:00 GMT+0800 (中国标准时间
参考[1] KRISACHAN: https://github.com/KRISACHAN[2]https://mp.weixin.qq.com/s/d8b90wcUltEKHq31ygKeIQ
