0.0.2 • Published 10 months ago

esy-tools v0.0.2

Weekly downloads
-
License
ISC
Repository
-
Last release
10 months ago

esy-tools

简介

  1. 收集常用的js方法
  2. 兼容性IE9+
  3. 内置一些特殊效果,如按钮点击水波纹效果等
  4. 内置一些常用正则匹配规则
  5. 内置一些城市及地区列表

安装

npm

    npm i esy-tools

pnpm(推荐使用)

    pnpm i esy-tools

yarn

    yarn i esy-tools

getBCR 获取元素的尺寸/位置

const div = document.createElement('div')
const bcr = getBCR(div)
// 打印结果{width:?,height:?,left:?,right:?,top:?,bottom:?,x:?,y:?}
console.log(bcr)

getClientXY 获取鼠标/触摸事件触发时的坐标

let obj
const div = document.createElement('div')
div.onclick = (e) => {
    obj = getClientXY(e)
}
// 触摸事件
// div.ontouchstart = (e) =>{
//     obj = getClientXY(e)
// }
// 打印结果 {x:?,y:?}
console.log(obj)

createRipple/removeRipple 元素添加/移除-水波纹效果

// css样式
// .left-0 {
//     left: 0;
// }
// .absolute {
//     position: absolute;
// }
// .top-0 {
//     top: 0;
// }
// .opacity-0 {
//     opacity: 0;
// }
// .z-100 {
//     z-index: 100;
// }
// .bg-current {
//     background: currentColor;
// }
// .pointer-events-none {
//     pointer-events: none;
// }
// .ripple {
//     transition:
//         transform 0.2s cubic-bezier(0.68, 0.01, 0.62, 0.6),
//         opacity 0.14s linear;
//         will-change: transform, opacity;
// }
const div = document.createElement('div')
// 需要添加对应的样式
div.classList.add('ripple')
div.onmousedown = createRipple(div)
div.onmouseup = removeRipple(div)

requestAnimationFrame 按照浏览器帧率节流函数执行次数

const test = () => {
    console.log('测试一下')
}
// 60帧率,大约16s间隔就会执行一次test函数
requestAnimationFrame(test)

getRoot 获取根节点

// 传入的元素的 css id名,可不传,默认就是'root'
// 不传时,如果页面没有root的id名称时,则自动获取body元素
const root = getRoot('root')
// 打印结果 <div id='root'></div> 或 <body>...</body>
console.log(root)

getEleBoundary 获取元素在父元素中的边距

const root = getRoot()
const div = document.createElement('div')
div.style = 'width:100px,height:100px'
root.appendChild(div)
const boundary = getEleBoundary(div)
// 打印结果{maxX:?,maxY:?,left:?,top:?}
console.log(boundary)

drawRoundedRect canvas 绘制圆角

const cvs = document.createElement('canvas')
const ctx = canvas.getContext('2d')
// 参数依次是 ctx, x 坐标, y 坐标, w 宽度, h 高度, r 圆角大小
drawRoundedRect(ctx, 0, 0, 100, 100, 20)

canvasRadiusImg canvas 绘制图片的圆角

const cvs = document.createElement('canvas')
const img = document.createElement('image')
// img.src = ?
const ctx = canvas.getContext('2d')

// 参数依次是 ctx, img 元素, x 坐标, y 坐标, w 宽度, h 高度, r 圆角大小
drawRoundedRect(ctx, img, 0, 0, 100, 100, 20)

isSupportCssKey 检测 css 属性兼容性

// 属性名/属性值 可不传 默认是 -webkit-line-clamp, 2
const isSupport = isSupportCssKey('-webkit-line-clamp', '2')

// 打印结果 true / false
console.log(isSupport)

getElementStyle 获取元素计算后的样式

const div = document.createElement('div')
const { fontSize } = getElementStyle(div)
// 打印结果 ?
console.log(fontSize)

getAllChildNodes 获取某个节点下的所有子节点

const div = document.createElement('div')
const nodes = getAllChildNodes(div)
// 打印结果 [?]
console.log(nodes)

动画相关的常量

// 动画时长 300
ANIMATION_TIME

// 淡入动画效果 [{ opacity: 0 }, { opacity: 1 }]
APPEAR_ANIMATION

// 淡出动画效果 [{ opacity: 1 }, { opacity: 0 }]
DISAPPEAR_ANIMATION

insertElement 创建元素插入到 body 中

const div = document.createElement('div')
// 第二个参数传 true时,会自动生成style标签插入到head中,设置html/body 禁止滚动
insertElement(div, false)

getScrollTop/getScrollLeft 获取页面滚动卷起的顶部/左边距离

const div = document.createElement('div')
const sTop = getScrollTop(div)
const sLeft = getScrollLeft(div)
// 打印结果 ? ?
console.log(sTop, sLeft)

scrollTo 元素滚动到指定位置

const div = document.createElement('div')
// top/left 滚动的指定y/x轴的距离. duration 滚动到指定为止所需要的时间, animation 控制滚动的速度曲线
scrollTo(div, { top: 100, left: 0, duration: 300, animation: (_v) => _v })

classEsy css 类名拼接

const cls = classEsy(['button', true ? '' : 'hidden', 'small'], 'other')
// 打印结果 button small other
console.log(cls)

classBem css 类名拼接

const cls = classEsy('--prefix', 'button', [true ? 'primary' : '', 'small'], 'other')
// 打印结果 --prefix-button --prefix-button-small --prefix-button-primary other
console.log(cls)

isImgLoading/isIntersectionObserver/imgLazyload/imgLazyloadScroll

处理图片懒加载的兼容性判断 (v0.0.2)

// isImgLoading() 原生img标签是否支持loading属性
// isIntersectionObserver() 浏览器是否支持IntersectionObserver API
// 图片懒加载(优先级高->低 loading -> IntersectionObserver -> scroll)
// loading 的情况比较简单,此处不做处理
const img = document.createElement('image')
// 设置元素的自定义属性:data-id 和 data-src 是必要属性
// data-id 绑定回调 data-src 绑定url
img.setAttribute('data-id', 'test-001')
img.setAttribute('data-src', 'https://?')
// 在图片组件挂载时调用
imgLazyload(img)
// imgLazyloadScroll 监听scroll/touchmove + getBoundingClientRect 实现
// 支持传两个参数:参数1-函数执行的回调 参数2-监听执行函数节流的间隔 参数3-元素距离顶部多少距离时开始加载
// 函数返回:移除监听事件的方法,在组件卸载时执行
const removeLister = imgLazyloadScroll()

initRem 移动端适配

// rem 实现适配,参数是375屏幕时的文字大小,默认是16px,可传入修改
// 放在项目入口即可
initRem(12)

observer/viewClientMap 监听元素是否在可视窗口

const div = document.createElement('div')
// 设置元素的自定义属性
div.setAttribute('data-id', 'test-id')
viewClientMap.set('show-test-id', () => {
    // 元素进入可视窗口时执行的函数
})
viewClientMap.set('hidden-test-id', () => {
    // 元素离开可视窗口时执行的函数
})
// 监听元素
observer.observe(div)
// 移除监听
observer.unobserve(div)

getDataType 获取数据在 js 中的格式

const t1 = getDataType(12)
const t2 = getDataType('12')
const t3 = getDataType(true)
const t4 = getDataType(new Date())
// 打印结果 number string boolean date
// 支持 string|number|null|boolean|undefined|array|object|map|function|regexp|date
console.log(t1, t2, t3, t4)

isPromise 判断传入的参数是否是Promise

const fn = async () => {
    await () => {}
}
const t = isPromise(fn)
// 打印结果 true
console.log(t)

isArray 判断是否是数组

const t = isArray([])
// 打印结果 true
console.log(t)

isObject 判断是否是对象,排除date/regexp等

const t1 = isObject({})
const t2 = isObject([])
// 打印结果 object array
console.log(t1, t2)

isEmpty 空判断

const t1 = isObject({})
const t2 = isObject([])
// 打印结果 true true
console.log(t1, t2)

isEmptyObject 空对象判断

const t1 = isObject({})
const t2 = isObject([])
// 打印结果 true true
console.log(t1, t2)

omit 忽略对象中的某一个键值对

const t1 = { a: 1, b: 2 }
const t2 = omit(t1, ['a'])
// 打印结果 { b: 2 }
console.log(t2)

pick 抽出对象中的某一些键值返回一个新的对象

const t1 = { a: 1, b: 2 }
const t2 = pick(t1, ['a'])
// 打印结果 { a: 1 }
console.log(t2)

debounce/throttle 防抖/节流函数

const fn = () => ({ a: 1, b: 2 })
// 300ms 内点击会重置点击事件
const t2 = debounce(fn, 300)
// 300ms 内点击会触发一次函数执行
const t3 = throttle(fn, 300)

copyText 复制文字

copyText('复制文字')
    .then(() => {
        // 复制成功的处理
        console.log('复制成功')
    })
    .catch(() => {
        console.log('复制失败')
    })

getRandomNumber 获取随机数

// 最大只能返回16位
const num1 = getRandomNumber()
const num2 = getRandomNumber(16)
// 打印结果 4个随机数 16个随机数
console.log(num1, num2)

openFolder 打开上传文件的弹窗

const ipt = document.createElement('input')
ipt.onclick = () => {
    // 参数1 文件类型 参数2 是否支持同时上传多个文件
    openFolder('.zip', false)
}

stopDefault/stopPropagation 阻止默认/冒泡事件

const ipt = document.createElement('input')
ipt.onclick = (e) => {
    stopDefault(e)
    stopPropagation(e)
}

arrayFillcb/arrayFill 填充一定长度的数组

// for循环实现
const arr1 = arrayFillcb(4)
// 优先调用 Array 的 fill 方法,其次 for 循环实现
const arr2 = arrayFill(4)
// 打印结果 [1, 2, 4, 4] [?, ?, ?, ?]
console.log(arr1, arr2)

getCommonDivisor 获取最大公约数

const n = getCommonDivisor(4, 2)
// 打印结果 2
console.log(n)

simplestFraction 获取最简分式

const n = simplestFraction(2, 4)
// 打印结果 1/2
console.log(n)

zeroFill 数字补0

const s1 = zeroFill(2, 2)
const s2 = zeroFill(2, 2, false)
// 打印结果 '002' '200'
console.log(s1, s2)

getRandomLetter 获取一个随机字母

const s1 = getRandomLetter()
// 打印结果 '?'
console.log(s1)

uuid 生成一个唯一id

const s1 = uuid()
// 打印结果 '?????-?????-?????-?????'
console.log(s1)

getHMSTime 将时间秒转化为时分秒

const s1 = getHMSTime(70)
// 打印结果 '00:01:10'
console.log(s1)

getCountDownTime 格式化倒计时的时间

// 主要用于倒计时时的展示
const s1 = getCountDownTime(70)
// 打印结果 {d, h, m, s} 天 时 分 秒
console.log(s1)

正则表达式

// 纯数字 /^[0-9]+$/
REG_NUMBER

// 纯小写字母 /^[a-z]+$/
REG_LETTER_SMALL

// 纯大写字母 /^[A-Z]+$/
REG_LETTER_BIG

// 字母/下划线开头长度6-18位的密码 /^[a-z_A-Z]\w{5, 17}$/
REG_PASSWORD

// 身份证号 /^\d{15}|\d{18}$/
REG_ID

// 一个或者多个汉字 /^[\u4e00-\u9fa5]+$/
REG_CHINESE

// 双字节字符 /^[\x00-\xff]$/
REG_DOUBLE_CHAR

// 首位固定数字1,后接5-10个数字 /^1[0-9]{5,10}$/
REG_NUMBER_6_11

// 银行卡号 /^[1-9]([0-9]{9,18})$/
REG_BANK_NUMBER

// QQ号 /^[1-9]([0-9]{4,10})$/
REG_QQ

// 微信 /^[a-zA-Z]{1}[-_a-zA-Z0-9]{5,19}$/
REG_WECHAT

// 外链资源头 /^((http|https|ftp|rtsp|mms)?:\/\/)/
REG_PROTOCOL

// 手机号码 /^1[3-9]\d{9}$/
REG_MOBILE

// 邮箱 /^[A-Za-z0-9-._]+@[A-Za-z0-9-]+(.[A-Za-z0-9]+)*(.[A-Za-z]{2,6})$/
REG_MAILBOX

// 手机端 /(Android|webOS|iPhone|iPod|BlackBerry|ios|Windows Phone|Phone|IOS)/i
REG_IS_MOBILE

// 手机端-IOS /iPad|iPhone|iPod/i
REG_IS_IOS

// 手机端-Android /Android/i
REG_IS_ANDROID

// 带有小数点数字 /^([+-]?)?\d+(\.\d*)?$/
REG_NUMBER_POIT

// 数字千分位 /(\d)(?=(\d{3})+(?!\d))/g
REG_FORMAT_DIGIT

// 数字千分位反替换 /\$\s?|([,|W]*)/g
REG_NO_FORMAT_DIGIT

// 国际手机号码正则表达式 /^((00){1}[1-9]{1}[0-9]{1,3}|86|\+86)?1[3458]\d{9}$/
REG_COM_MOBILE

// base64 资源 /^data:image\/png;base64/
REG_BASE64

// 电话验证 区号(0开头)-号码 /^0\d{2,3}-?\d{7,8}$/
REG_PHONE

// html 标签 /<(.*)>(.*)<\/(.*)>|<(.*)\/>/
REG_HTML

// 字符串首尾空格 /(^\s*)|(\s*$)/
REG_SE_SPACE

// 移动端判断
isIOS() // true / false
isAndroid() // true / false
isMobile() // true / false

kiloDigit 数字千分位处理

const n1 = kiloDigit(+123456789)
const n2 = kiloDigit(-123456789.23)
// 123,456,789  -123,456,789.23
console.log(n1, n2)

CITYS 城市数组

// 数据结构
// [
//     {
//         text: '北京',
//         key: '0',
//         children: [
//             {
//                 text: '北京市',
//                 key: '0',
//                 children: [
//                     {
//                         text: '东城区',
//                         key: '0'
//                     },
//                     ...
//                 ]
//             },
//             ...
//         ]
//     },
//     ...
// ],
console.log(CITYS)

getTodayDate 日期格式化 (v0.0.2)

const y1 = getTodayDate()
const y2 = getTodayDate(20220502)
const y3 = getTodayDate(20220502, { y: '年', m: '月', d: '日' })
// 2024-10-17  2022-05-02 2022年05月02日
console.log(y1, y2, y3)

escapedHTML 转义html标签 (v0.0.2)

const h1 = escapedHTML('<div></div>')
// &lt;div&gt;&lt;/div&gt;;
console.log(h1)

comAnimate/animateFn 添加动画/过渡效果 (v0.0.2)

// 获取根节点用于测试
const root = document.getElementById('root')
// 根节点添加点击事件
root.onclick = () => {
    // 动态生成虚拟节点
    const insertTarget = document.createElement('div')
    // 加点初始样式方便观察
    insertTarget.style.cssText = 'width:100px;height:100px;background:red;'
    root.appendChild(insertTarget)
    // 接收三个参数 1. 元素节点 2. 动画数组 3. 动画时长
    animateFn(insertTarget, this.esyTools.APPEAR_ANIMATION, this.esyTools.ANIMATION_TIME)
}
// 注:comAnimate 只是将animateFn封装在内部做兼容,如果浏览器支持animate方法则直接调用
// animate方法,参数2/3就是animate方法的参数