common.js

作者: locky丶 | 来源:发表于2020-06-08 15:09 被阅读0次

    获取url参数

    export const getQueryString = (name) => {
        const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        const search = window.location.search.split('?')[1] || '';
        const r = search.match(reg) || [];
        return r[2];
    }
    

    动态引入js

    export const injectScript = (src) => {
        const s = document.createElement('script');
        s.type = 'text/javascript';
        s.async = true;
        s.src = src;
        const t = document.getElementsByTagName('script')[0];
        t.parentNode.insertBefore(s, t);
    }
    

    根据url地址下载

    export const download = (url) => {
        var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
        var isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;
        if (isChrome || isSafari) {
            var link = document.createElement('a');
            link.href = url;
            if (link.download !== undefined) {
                var fileName = url.substring(url.lastIndexOf('/') + 1, url.length);
                link.download = fileName;
            }
            if (document.createEvent) {
                var e = document.createEvent('MouseEvents');
                e.initEvent('click', true, true);
                link.dispatchEvent(e);
                return true;
            }
        }
        if (url.indexOf('?') === -1) {
            url += '?download';
        }
        window.open(url, '_self');
        return true;
    }
    

    获取滚动的坐标

    export const getScrollPosition = (el = window) => ({
        x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
        y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
    });
    

    滚动到顶部

    export const scrollToTop = () => {
        const c = document.documentElement.scrollTop || document.body.scrollTop;
        if (c > 0) {
            window.requestAnimationFrame(scrollToTop);
            window.scrollTo(0, c - c / 8);
        }
    }
    

    拦截粘贴板

    export const copyTextToClipboard = (value) => {
        var textArea = document.createElement("textarea");
        textArea.style.background = 'transparent';
        textArea.value = value;
        document.body.appendChild(textArea);
        textArea.select();
        try {
            var successful = document.execCommand('copy');
        } catch (err) {
            console.log('Oops, unable to copy');
        }
        document.body.removeChild(textArea);
    }
    

    去除空格,type: 1-所有空格 2-前后空格 3-前空格 4-后空格

    export const trim = (str, type) => {
        type = type || 1
        switch (type) {
            case 1:
                return str.replace(/\s+/g, "");
            case 2:
                return str.replace(/(^\s*)|(\s*$)/g, "");
            case 3:
                return str.replace(/(^\s*)/g, "");
            case 4:
                return str.replace(/(\s*$)/g, "");
            default:
                return str;
        }
    }
    

    字符转换,type: 1:首字母大写 2:首字母小写 3:大小写转换 4:全部大写 5:全部小写

    export const changeCase = (str, type) => {
        type = type || 4
        switch (type) {
            case 1:
                return str.replace(/\b\w+\b/g, function (word) {
                    return word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase();
    
                });
            case 2:
                return str.replace(/\b\w+\b/g, function (word) {
                    return word.substring(0, 1).toLowerCase() + word.substring(1).toUpperCase();
                });
            case 3:
                return str.split('').map(function (word) {
                    if (/[a-z]/.test(word)) {
                        return word.toUpperCase();
                    } else {
                        return word.toLowerCase()
                    }
                }).join('')
            case 4:
                return str.toUpperCase();
            case 5:
                return str.toLowerCase();
            default:
                return str;
        }
    }
    

    函数节流器

    export const debouncer = (fn, time, interval = 200) => {
        if (time - (window.debounceTimestamp || 0) > interval) {
            fn && fn();
            window.debounceTimestamp = time;
        }
    }
    

    在字符串中插入新字符串

    export const insertStr = (soure, index, newStr) => {
        var str = soure.slice(0, index) + newStr + soure.slice(index);
        return str;
    }
    

    判断两个对象是否键值相同

    export const isObjectEqual = (a, b) => {
        var aProps = Object.getOwnPropertyNames(a);
        var bProps = Object.getOwnPropertyNames(b);
    
        if (aProps.length !== bProps.length) {
            return false;
        }
    
        for (var i = 0; i < aProps.length; i++) {
            var propName = aProps[i];
    
            if (a[propName] !== b[propName]) {
                return false;
            }
        }
        return true;
    }
    

    16进制颜色转RGBRGBA字符串

    export const colorToRGB = (val, opa) => {
    
        var pattern = /^(#?)[a-fA-F0-9]{6}$/; //16进制颜色值校验规则
        var isOpa = typeof opa == 'number'; //判断是否有设置不透明度
    
        if (!pattern.test(val)) { //如果值不符合规则返回空字符
            return '';
        }
    
        var v = val.replace(/#/, ''); //如果有#号先去除#号
        var rgbArr = [];
        var rgbStr = '';
    
        for (var i = 0; i < 3; i++) {
            var item = v.substring(i * 2, i * 2 + 2);
            var num = parseInt(item, 16);
            rgbArr.push(num);
        }
    
        rgbStr = rgbArr.join();
        rgbStr = 'rgb' + (isOpa ? 'a' : '') + '(' + rgbStr + (isOpa ? ',' + opa : '') + ')';
        return rgbStr;
    }
    

    追加url参数

    export const appendQuery = (url, key, value) => {
        var options = key;
        if (typeof options == 'string') {
            options = {};
            options[key] = value;
        }
        options = $.param(options);
        if (url.includes('?')) {
            url += '&' + options
        } else {
            url += '?' + options
        }
        return url;
    }
    

    1

    
    

    1

    
    

    相关文章

      网友评论

          本文标题:common.js

          本文链接:https://www.haomeiwen.com/subject/vhtrtktx.html