JS常用工具类

1.获取当前dom相对于document的偏移量

 1 const getOffset = el => {
 2     console.log(el);
 3     const {top, left} = el.getBoundingClientRect();
 4     const {scrollTop, scrollLeft} = document.body;
 5     return {
 6         top: top + scrollTop,
 7         left: left + scrollLeft
 8     };
 9 };
10 console.log(getOffset(document.querySelector('div')));
11 //{top: 200, left: 8}

2.禁止网页复制粘贴

1 document.querySelector('html').oncopy = () => false;
2 document.querySelector('html').onpaste = () => false;

3.去除字符串前面空格

1 const trimStart = str => str.replace(new RegExp('^([\\s]*)(.*)$'), '$2');
2 console.log(trimStart(' abc1'));
3 //abc

4.时间格式化

 1 Date.prototype.Format = function (fmt) {
 2     var o = {
 3         'M+': this.getMonth() + 1, //月份
 4         'd+': this.getDate(), //日
 5         'h+': this.getHours(), //小时
 6         'm+': this.getMinutes(), //分
 7         's+': this.getSeconds(), //秒
 8         'q+': Math.floor((this.getMonth() + 3) / 3), //季度
 9         S: this.getMilliseconds() //毫秒
10     };
11     if (/(y+)/.test(fmt)) {
12         fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
13     }
14     for (var k in o) {
15         if (new RegExp('(' + k + ')').test(fmt)) {
16             fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
17         }
18     }
19     return fmt;
20 };
21 console.log(new Date().Format('yyyy年MM月dd日 hh时mm分ss秒'));
22 //2020年08月09日 14时54分27秒
23 
24 console.log(new Date().Format('yyyy-MM-dd hh:mm:ss'));
25 //2020-08-09 14:54:27
26 
27 console.log(new Date().Format('yyyy-MM-dd'));
28 //2020-08-09
29 
30 console.log(new Date().Format('hh:mm:ss'));
31 //14:54:27
32 
33 console.log(new Date().Format('yyyy-MM'));
34 //2020-08
35 
36 console.log(new Date().Format('hh:mm'));
37 //14:54
38 
39 console.log(new Date().Format('MM-dd'));
40 //08-09

5.查询url参数

 1 String.prototype.urlQuery = function () {
 2     var url = this.split('?')[1].split('&');
 3     this.urlobj = {};
 4     for (var i = 0; i < url.length; i += 1) {
 5         var cell = url[i].split('=');
 6         var key = cell[0];
 7         var val = cell[1];
 8         this.urlobj['' + key + ''] = val;
 9     }
10     return this.urlobj;
11 };
12 var url = 'http://www/baidu.com?name=12&age=1000';
13 // 查询所有参数
14 console.log(url.urlQuery());
15 // {name: "12", age: "1000"}
16 // 查询某一个参数
17 console.log(url.urlQuery().name);

6.电话模糊处理

 1 function fn(option) {
 2     // 判断传入的手机号码位数,不符合则返回提示
 3     if (String(option.mobile).length > 11) {
 4         return '手机号码格式错误';
 5     } else {
 6         let newmobile = String(option.mobile).slice(0, option.start) + '*'.repeat(option.num) + String(option.mobile).slice(option.start + option.num, String(option.mobile).length);
 7         // 如果新的手机号位数过长,则返回固定11位手机号
 8         return newmobile.slice(0, 11);
 9     }
10 }
11 console.log(fn({mobile: 13012345678, start: 3, num: 3}));
12 //130***45678

7.rgb转换为16进制

 1 function colorRGBtoHex(color) {
 2     var rgb = color.split(',');
 3     var r = parseInt(rgb[0].split('(')[1]);
 4     var g = parseInt(rgb[1]);
 5     var b = parseInt(rgb[2].split(')')[0]);
 6     var hex = '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
 7     return hex;
 8 }
 9 console.log(colorRGBtoHex('rgb(0,0,0)'));
10 //#000000

8.对象扁平化

 1 const flatten = function (obj) {
 2     var result = {};
 3     function recurse(src, prop) {
 4         var toString = Object.prototype.toString;
 5         if (toString.call(src) == '[object Object]') {
 6             var isEmpty = true;
 7             for (var p in src) {
 8                 isEmpty = false;
 9                 recurse(src[p], prop ? prop + '.' + p : p);
10             }
11             if (isEmpty && prop) {
12                 result[prop] = {};
13             }
14         } else if (toString.call(src) == '[object Array]') {
15             var len = src.length;
16             if (len > 0) {
17                 src.forEach(function (item, index) {
18                     recurse(item, prop ? prop + '.[' + index + ']' : index);
19                 });
20             } else {
21                 result[prop] = [];
22             }
23         } else {
24             result[prop] = src;
25         }
26     }
27     recurse(obj, '');
28     const _ = [];
29     Object.keys(result).forEach(item => {
30         _.push(`${item}=${result[item]}`);
31     });
32 
33     return _.join('&');
34 };
35 
36 console.log(flatten({a: {b: {c: {d: 1, e: 2}, f: 3}, h: 5}, g: 4}));
37 // a.b.c.d=1&a.b.c.e=2&a.b.f=3&a.h=5&g=4

 9.防抖

const debounce = (func, wait = 3000, immediate = true) => {
            let timeout = null;
            return function () {
                let context = this;
                let args = arguments;
                if (timeout) clearTimeout(timeout);
                if (immediate) {
                    var callNow = !timeout; //true
                    timeout = setTimeout(() => {
                        timeout = null;
                    }, wait); //定时器ID
                    if (callNow) func.apply(context, args);
                } else {
                    timeout = setTimeout(function () {
                        func.apply(context, args);
                    }, wait);
                }
            };
        };

10.节流

// 时间戳方案
        function throttle(fn, wait = 2000) {
            var pre = Date.now();
            return function () {
                var context = this;
                var args = arguments;
                var now = Date.now();
                if (now - pre >= wait) {
                    fn.apply(context, args);
                    pre = Date.now();
                }
            };
        }
        // 定时器方案
        function throttle(fn, wait = 3000) {
            var timer = null;
            return function () {
                var context = this;
                var args = arguments;
                if (!timer) {
                    timer = setTimeout(function () {
                        fn.apply(context, args);
                        timer = null;
                    }, wait);
                }
            };
        }

 11.使用iframe下载文件

const exportFile = ({ url, params }) => {
    if (url) {
        var _iframe = document.getElementById('download-file');
        if (_iframe) {
            document.body.removeChild(_iframe);
        }
        var _iframe = document.createElement('iframe');
        _iframe.style.display = 'none';
        _iframe.id = 'download-file';
        if (params) {
            _iframe.src = `${url}?${parseParams(params)}`;
        } else {
            _iframe.src = url;
        }
        document.body.appendChild(_iframe);
    }
};

12.将参数转化为url拼接格式

const parseParams = params => {
    if (params && typeof params == 'object') {
        let str = '';
        Object.keys(params).forEach(key => {
            str += `${key}=${params[key]}&`;
        });
        return str.substring(0, str.length - 1);
    }
};

13.获取文件后缀

cosnt getFileExt = fileName => {
    //获取最后一个.的位置
    var index = fileName.lastIndexOf('.');
    //获取后缀
    var ext = fileName.substr(index + 1);
    return ext;
};

14.获取url中的文件名

// url = 'http://xxxx/xxx/xx/file.png'
const getFileName = url => {
    let num = url.lastIndexOf('/') + 1;
    let name = url.substring(num);
    return name;
};

15.判断文件类型是否符合

const getFileType = (ext, target = ['xls', 'xlsx']) => {
    return target.indexOf(ext.toLowerCase()) !== -1;
};

16.是否以指定名称开头

const isAppointName = (name, fullName) => {
    if (name && fullName) {
        const nameLen = name.length;
        return fullName.substr(0, nameLen) === name;
    }
};
isAppointName(test,test123)
//true

17.数组中根据某个属性排序

const compareByProp = prop => {
    return function (obj1, obj2) {
        var val1 = obj1[prop];
        var val2 = obj2[prop];
        if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
            val1 = Number(val1);
            val2 = Number(val2);
        }
        if (val1 < val2) {
            return -1;
        } else if (val1 > val2) {
            return 1;
        } else {
            return 0;
        }
    };
};

18.生成UUID

const generateUUID = () => {
    var d = new Date().getTime();
    if (window.performance && typeof window.performance.now === 'function') {
        d += performance.now(); //use high-precision timer if available
    }
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x3) | 0x8).toString(16);
    });
    return uuid;
};

19.将file转为blob

const fileToBlob = file => {
    return new Promise(resolve => {
        resolve(window.URL.createObjectURL(file));
    });
};

20.将file转为base64

const fileToBase64 = file => {
    return new Promise(resolve => {
        let fileReader = new FileReader();
        fileReader.readAsDataURL(file);
        fileReader.onload = () => {
            resolve(fileReader.result);
        };
    });
};

21.将base64转为file

       // base64转file
     const  base64Tofile = (base64, filename) => {
            var arr = base64.split(','),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new File([u8arr], filename, { type: mime });
        },

22.将file地址转为base64

const fileUrlToBase64 = src => {
    function getBase64Image(img, width, height) {
        var canvas = document.createElement('canvas');
        canvas.width = width ? width : img.width;
        canvas.height = height ? height : img.height;
        const ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        var dataURL = canvas.toDataURL();
        return dataURL;
    }
    return new Promise(resolve => {
        const image = new Image();
        image.crossOrigin = '';
        image.src = src;
        image.onload = function () {
            resolve(getBase64Image(image));
        };
    });
};

23.是否是空对象

const isEmptyObject = obj => {
    return Object.keys(obj).length === 0;
};

 24.压缩图片

  const compressImg = ({ width, quality = 0.7, file, maxSize }) => {
            const _this = this;
            // 最大接受图片尺寸 2M
            maxSize = maxSize || 2 * 1024 * 1024;
            return new Promise(async (resolve, reject) => {
                if (!file) {
                    reject(new Error('img 不存在'));
                } else {
                    // 获取图片类型
                    let imgType = file.type;
                    // 获取图片名称
                    let imgName = file.name;
                    // 获取图片base64
                    let base64 = await this.fileToBase64(file);
                    let image = new Image();
                    image.src = base64;
                    image.onload = function () {
                        // 获得长宽比例
                        const scale = this.width / this.height;
                        //创建一个canvas
                        const canvas = document.createElement('canvas');
                        //获取上下文
                        const context = canvas.getContext('2d');
                        //获取压缩后的图片宽度,如果width为-1,默认原图宽度
                        canvas.width = width ? width : this.width;
                        canvas.height = width ? parseInt(width / scale) : this.height;
                        //把图片绘制到canvas上面
                        context.drawImage(image, 0, 0, canvas.width, canvas.height);
                        //压缩图片,获取到新的base64Url
                        const newBase64 = canvas.toDataURL(imgType, quality);
                        //将base64转化成文件流
                        const resultFile = _this.base64Tofile(newBase64, imgName);
                        let blobSrc = '';
                        if (resultFile.size > maxSize) {
                            _this.compressImg({ file: resultFile }).then(file => resolve(file));
                        } else {
                            // 压缩图片 获取到新的blob地址
                            canvas.toBlob(
                                function (blob) {
                                    blobSrc = URL.createObjectURL(blob);
                                    resolve({ resultFile, blobSrc, newBase64 });
                                },
                                imgType,
                                quality
                            );
                        }
                    };
                }
            });
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值