JavaScript常用工具函数

1、加载js || css || style

const loadRes = function (name, type, fn) {
    let ref
    if (type === "js") {    // 外部js
        ref = document.createElement("script")
        ref.setAttribute("type", "text/javascript")
        ref.setAttribute("src", name)
    } else if (type === "css") {    // 外部css
        ref = document.createElement("link")
        ref.setAttribute("rel", "stylesheet")
        ref.setAttribute("type", "text/css")
        ref.setAttribute("href", name)
    } else if (type === "style") {  // style
        ref = document.createElement("style")
        ref.innerHTML = name
    }
    if (typeof ref !== "undefined") {
        document.getElementsByTagName("head")[0].appendChild(ref)
        ref.onload = function () {  // 加载完成执行
            typeof fn === "function" && fn()
        }
    }
}

2、获取url参数

const getUrlParam = function (name) {   // 获取url参数
    let reg = new RegExp('(^|&?)' + name + '=([^&]*)(&|$)', 'i')
    let r = window.location.href.substr(1).match(reg)
    if (r != null) {
        return decodeURI(r[2])
    }
    return undefind
}

3、本地储存

const store = {     // 本地储存
    set: function (name, value, key) {  // 设置
        let d = new Date()
        let time = 0
        day = (typeof(day) === "undefined" || !day) ? 1 : day   // 时间,默认存储一天
        time = d.setHours(d.getHours() + (24 * day))    // 毫秒
        localStorage.setItem(name, JSON.stringify({
            data: value,
            time: time
        }))
    },
    get: function (name) {  // 获取
        let data = localStorage.getItem(name)
        if (!data) {
            return null
        }
        let obj = JSON.parse(data)
        if (new Date().getTime() > obj.time) {  // 过期
            localStorage.removeItem(name)
            return null
        } else {
            return obj.data
        }
    },
    clear: function (name) {    // 清空
        if (name) {     // 删除key为name的缓存
            localStorage.removeItem(name)
        } else {
            localStorage.clear()
        }
    }
}

4、JS获取元素样式(支持内联)

const getRealStyle = function (obj, styleName) {
    let realStyle = null
    if (obj.currentStyle) {
        realStyle = obj.currentStyle[styleName]
    } else if (window.getComputedStyle) {
        realStyle = window.getComputedStyle(obj, null)[styleName]
    }
    return realStyle
}

5、时间格式化

const formatDate = function (fmt, date) {   // 格式化成 yyyy-MM-dd hh:mm:ss
    if (typeof date !== "object") {
        date = !date ? new Date() : new Date(date)
    }
    let o = {
        "M+": date.getMonth() + 1,
        "d+": date.getDate(),
        "h+": date.getHours(),
        "m+": date.getMinutes(),
        "s+": date.getSeconds(),
        "q+": Math.floor((date.getMonth() + 3) / 3),    // 季度
        "S": date.getMilliseconds() // 毫秒
    }
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    for (let k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' +
            o[k]).substr(('' + o[k]).length)))
        }
    }
    return fmt
}

6、设备判断:android、ios、web

const isDevice = function () {
    if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
        return "iOS"
    } else if (/(Android)/i.test(navigator.userAgent)) {
        return "Android"
    }
    return "Web"
}

7、判断是否为微信

const isWx = function () {
    let ua = window.navigator.userAgent.toLowerCase()
    if (ua.match(/MicroMessenger/i) === 'micromessenger') {
        return true
    }
    return false
}

8、文本复制

const copyTxt = function (text, fn) {
    if (typeof document.execCommand !== "function") {
        console.log("复制失败,请长按复制")
        return
    }
    let dom = document.createElement("textarea")
    dom.value = text
    dom.setAttribute("style", "display: block;width: 1px;height: 1px;")
    document.body.appendChild(dom)
    dom.select()
    let result = document.execCommand("copy")
    document.body.removeChild(dom)
    if (result) {
        console.log("复制成功")
        typeof fn === "function" && fn()
        return
    }
    if (typeof document.createRange !== "function") {
        console.log("复制失败,请长按复制")
        return
    }
    let range = document.createRange()
    let div = document.createElement("div")
    div.innerHTML = text
    div.setAttribute("style", "height: 1px;fontSize: 1px;overflow: hidden;")
    document.body.appendChild(div)
    range.selectNode(div)
    let selection = window.getSelection()
    console.log(selection)
    if (selection.rangeCount > 0) {
        selection.removeAllRanges()
    }
    selection.addRange(range)
    document.execCommand("copy")
    typeof fn === "function" && fn()
    console.log("复制成功")
}

9、判断是否是一个数组

const isArray = function (arr) {
    return Object.prototype.toString.call(arr) === "[object Array]"
}

10、判断两个数组是否相等

const arrayEqual = function (arr1, arr2) {
    if (arr1 === arr2) return true
    if (arr1.length != arr2.length) return false
    for (let i = 0; i < arr1.length; i++) {
        if (arr1[i] !== arr2[i]) return false 
    }
    return true
}

11、时间与时间戳的转换

const stamp = {
    // 时间转时间戳
    getTime(time) {
        let date = time ? new Date(time) : new Date()
        return Math.round(date.getTime() / 1000)
    },
    // 时间戳转时间
    timeToStr(time, fmt) {
        return new Date(time * 1000).pattern(fmt || 'yyyy-MM-dd')
    }
}

12、判断图片加载完成

const imgLoadAll = function (arr, callback) {
    let arrImg = []
    for (let i = 0; i < arr.length; i++) {
        let img = new Image()
        img.src = arr[i]
        img.onload = function () {
            arrImg.push(this)
            if (arrImg.length == arr.length) {
                callback && callback()
            }
        }
    }
}

13、音频加载完成操作

const loadAudio = function (src, callback) {
    let audio = new Audio(src)
    audio.onloadedmetadata = callback
    audio.src = src
}

14、光标所在位置插入字符

const insertAtCursor = function (dom, val) {
    if (document.selection) {
        dom.focus()
        let sel = document.selection.createRange()
        sel.text = val
        sel.select()
    } else if (dom.selectionStart || dom.selectionStart == '0') {
        let startPos = dom.selectionStart
        let endPos = dom.selectionEnd
        let restoreTop = dom.scrollTop
        dom.value = dom.value.substring(0, startPos) + val + dom.value.substring(endPos, dom.value.length)
        if (restoreTop > 0) {
            dom.scrollTop = restoreTop
        }
        dom.focus()
        dom.selectionStart = startPos + val.length
        dom.selectionEnd = startPos + val.length
    } else {
        dom.value += val
        dom.focus()
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容