Js commonly used some function encapsulation

var events = {
    /** * Get path parameter method Returns parameter value * @name Parameter name ** /
    getQueryString: function (name) {
        var reg = new RegExp("(^ | &)" + name + "= (/ ^ & *) (& | $)"."i");
        // window.location.search retrieves the rest of the url question mark
        var r = window.location.search.substr(1).match(reg);
        if(r ! =null) return unescape(r[2]);
        return null;
    },

    /** * Set cookie * @name Cookie name * @value Cookie value * @expireDays How many days after expiration ** /
    setCookie: function (name, value, expiredays) {
        var exdate = new Date(a);if(! expiredays ||isNaN(expiredays)) {
            expiredays = 1;
        }
        exdate.setDate(exdate.getDate() + expiredays);
        document.cookie = name + "=" + escape(value) + ((expiredays == null)?"" : "; expires=" + exdate.toGMTString());
    },

    /** * read cookie * @name Cookie name ** /
    getCookie: function (name) {
        var arr, reg = new RegExp("(^| )" + name + "= (/ ^; (*). | $)");
        if (arr = document.cookie.match(reg))
            return unescape(arr[2]);
        else
            return null;
    },

    /** * delete cookie * @name Cookie name ** /
    delCookie: function (name) {
        var exp = new Date(a); exp.setTime(exp.getTime() -1);
        var cval;
        var arr, reg = new RegExp("(^| )" + name + "= (/ ^; (*). | $)");
        if (arr = document.cookie.match(reg))
            cval = unescape(arr[2]);
        else
            cval = null;

        if(cval ! =null)
            document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
    },

    /** * Set localStorage * @name Parameter name * @value Parameter value Note: Only string ** / is available
    setLocalStorage: function (name, value) {
        if (typeofname ! = ="string") {
            name = JSON.stringify(name);
        }
        if (typeofvalue ! = ="string") {
            value = JSON.stringify(value);
        }
        localStorage.setItem(name, value);
    },

    /** * get the localStorage * @name parameter name * note: the results are all string ** /
    getLocalStorage: function (name) {
        if (typeofname ! = ="string") {
            name = JSON.stringify(name);
        }
        return localStorage.getItem(name);
    },

    /**
     * 删除 localStorage
     * @name 参数名
     * */
    delLocalStorage: function (name) {
        if (typeofname ! = ="string") {
            name = JSON.stringify(name);
        }
        localStorage.removeItem(name);
    },

    /** * clear localStorage * @clear() clear all localStorage ** /
    clearLocalStorage: function () {
        localStorage.clear();
    },

    /** * Set sessionStorage * @name parameter name * @value Parameter value Note: Only string ** / is available
    setSessionStorage: function (name, value) {
        if (typeofname ! = ="string") {
            name = JSON.stringify(name);
        }
        if (typeofvalue ! = ="string") {
            value = JSON.stringify(value);
        }
        sessionStorage.setItem(name, value);
    },

    /** ** get sessionStorage * @name parameter name * note: this is string ** /
    getSessionStorage: function (name) {
        if (typeofname ! = ="string") {
            name = JSON.stringify(name);
        }
        return sessionStorage.getItem(name);
    },

    /**
     * 删除 sessionStorage
     * @name 参数名
     * */
    delSessionStorage: function (name) {
        if (typeofname ! = ="string") {
            name = JSON.stringify(name);
        }
        sessionStorage.removeItem(name);
    },

    /** * clear sessionStorage * @clear() clear all localStorage ** /
    clearSessionStorage: function () {
        sessionStorage.clear();
    },

    /** * Obtain the current time * in the format YYYY-MM-DD hh: MM :ss */
    getNowTime: function () {
        var date = new Date(a);var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        var hour = date.getHours();
        var minute = date.getMinutes();
        var second = date.getSeconds();

        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        if (hour >= 1 && hour <= 9) {
            hour = "0" + hour;
        }
        if (minute >= 0 && minute <= 9) {
            minute = "0" + minute;
        }
        if (second >= 1 && second <= 9) {
            second = "0" + second;
        }

        var currentTime = year + "-" + month + "-" + strDate + "" + hour + ":" + minute + ":" + second;

        return currentTime;
    },

    /** * get the current timestamp unit ms ** /
    getNowTimeStamp: function () {
        var timestamp = new Date().getTime() + "";
        return timestamp;
    },

    * @dayCount * getYMDStr(0): current day, getYMDStr(1): next day, getYMDStr(-1): last day ** /
    getYMDStr: function (dayCount) {
        var dd = new Date(a); dd.setDate(dd.getDate() + dayCount);// Get the day after dayCount
        var y = dd.getFullYear();
        var m = (dd.getMonth() + 1) < 10 ? "0" + (dd.getMonth() + 1) : (dd.getMonth() + 1);// Get the date of the current month
        var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();// Get the current number, if less than 10, add 0
        return y + "-" + m + "-" + d; // return year month day
    },


    /** * Check whether it is Internet Explorer * @ActivexObject Only Internet Explorer has this plug-in ** /
    isIE: function () {
        var ms_ie = false;
        var ua = window.navigator.userAgent;
        var old_ie = ua.indexOf('MSIE ');
        var new_ie = ua.indexOf('Trident/');

        if ((old_ie > - 1) || (new_ie > - 1)) {
            ms_ie = true;
        }
        return ms_ie;
    },

    /** * Check whether it is PC ** /
    isPCBroswer: function () {
        return! (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent));
    },

    Call stopPropagation(e) ** / to stop event bubbles
    stopPropagation: function (e) {
        e = e || window.event;
        if (e.stopPropagation) { //W3C prevents bubbling methods
            e.stopPropagation();
        } else {
            e.cancelBubble = true; //IE prevents bubbling}},/** * a single array is de-duplicated → ["",""] * @array passes an array ** /
    delRepeat: function (array) {
        if(! (arrayinstanceof Array)) {
            console.warn("You're not passing an array type.");
            return false;
        }
        // There are many ways to lose weight, I chose this one
        var result = [];
        for (var i = 0; i < array.length; i++) {
            if (result.indexOf(array[i]) === - 1) { result.push(array[i]); }}return result;
    },

    [{},{}] * @array array * @attrName attribute name, what attribute name is used to determine whether the Json data is duplicate ** /
    delRepeatJson: function (array, attrName) {
        if(! (arrayinstanceof Array)) {
            console.warn("You're not passing an array type.");
            return false;
        }
        var temp = {};   // Use the name to judge the repetition
        var result = [];  // The last new array
        array.map(function (item, index) {
            if(! temp[item[attrName]]) { result.push(item); temp[item[attrName]] =true; }});return result;
    },

    @src Image to be compressed base64 Path * @width Maximum image width by default 1024 * @format Image format by default JPEG * @quality Image quality 0-1, The default 1 * @success() callback returns the compressed base64 path * */
    compressedImage: function (params) {
        var that = this;

        var initParams = {
            src: params.src || "".width: params.width || 1024.format: params.format || "jpeg".quality: params.quality || 1};var image = new Image();
        image.src = initParams.src;
        image.onload = function () {
            // Get the initial width and height of the image
            var width = image.width;
            var height = image.height;
            // Determine the width of the picture, and then set the width and height of the picture proportionally
            if (width > Number(initParams.width)) {
                width = Number(initParams.width);
                height = Math.ceil(Number(initParams.width) * (image.height / image.width));
            }

            // Redraw the image into the canvas
            var canvas = document.getElementById("compressCanvas");
            if(! canvas) {// Create a canvas canvas if there is no canvas to compress
                var body = document.body;
                canvas = document.createElement("canvas"); // Create the canvas tag
                canvas.id = "compressCanvas"; // Add an ID to the outer container
                canvas.style.position = "fixed";
                canvas.style.zIndex = "1";
                canvas.style.opacity = "0";
                canvas.style.top = "100%";
                canvas.style.left = "100%";
                body.appendChild(canvas);
            }

            var context = canvas.getContext("2d");
            canvas.width = width;
            canvas.height = height;
            context.beginPath();
            if(initParams.format ! = ="png") {
                context.fillStyle = "#ffffff";
                context.fillRect(0.0, width, height);
                context.fill();
                context.closePath();
            }
            context.drawImage(image, 0.0, width, height);
            var replaceSrc = canvas.toDataURL("image/" + initParams.format + "", initParams.quality); Canvas to DataURL(base64 format)

            params.success && params.success(replaceSrc);
        };
    },

    DataURL to File object * @dataURL base64 Path address * @filename User-defined File name ** /
    dataURLtoFile: function (dataURL, fileName) {
        var arr = dataURL.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});
    },

    DataURL into Blob object * @dataURI base64 Path address */
    dataURLtoBlob: function (dataURI) {
        var arr = dataURI.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 Blob([u8arr], {type: mime});
    },

    /** * get a range of random numbers * @min minimum * @max maximum ** /
    getRandomNum: function (min, max) {
        return Math.floor(Math.random() * (min - max) + max);
    },

    /** ** Gets a random color * @opacity default 1 ** /
    getRandomColor: function (opacity) {
        if(! opacity ||typeofopacity ! ="number") {
            opacity = 1
        }
        var red = Math.round(Math.random() * 255);
        var green = Math.round(Math.random() * 255);
        var blue = Math.round(Math.random() * 255);
        return "rgba(" + red + "," + green + "," + blue + "," + opacity + ")"; }};Copy the code

Usage:

Simple and bold: directly copy and paste to their own project in accordance with their own document path to introduce it!