js 个人笔记

/*
 * Created by lsw 2018-06
 */
; (function (window) {
    //js ready
    var ie = !!(window.attachEvent && !window.opera), wk = /webkit/(d+)/i.test(navigator.userAgent) && (RegExp.$1 < 525);
    var fn = [], run = function () { for (var i = 0; i < fn.length; i++)fn[i](); }, d = document; d.ready = function (f) {
        if (!ie && !wk && d.addEventListener) { return d.addEventListener('DOMContentLoaded', f, false); } if (fn.push(f) > 1) return;
        if (ie) (function () { try { d.documentElement.doScroll('left'); run(); } catch (err) { setTimeout(arguments.callee, 0); } })();
        else if (wk) var t = setInterval(function () { if (/^(loaded|complete)$/.test(d.readyState)) clearInterval(t), run(); }, 0);
    };
    //防止网页被嵌入框架的代码 
    try {
        window.top.location.hostname;
        if (top.location.hostname != window.location.hostname) {
            top.location.href = window.location.href;
        }
    }
    catch (e) {
        top.location.href = window.location.href;
    }
    //内部变量
    var variableObj = {
            msgTips: $(document.querySelector("#msgTips")),
            msgTipsBody: document.querySelector("#msgTipsBody"),
            url: window.location.href,
            keys: "AAnFauu4V6Zdwczo",
            progressBar: document.querySelector("#progressBar")
        },
        initialize = {
            create: function () {
                return function () {
                    this.initialize.apply(this, arguments);
                }
            },
            //reader初始化事件,或预操作
            reader: function () {
                let consoleConfig = {
                    o2Market: "欢迎访问:http://www.yishion.com.cn/ 
公众号:YISHION-GROUP 每周推送漂亮时尚好看的衣服!",
                    gongzonghao: window.location.origin +"/Content/YiSee/IMG/qrcode.jpg"
                };
                console.log("%c" + consoleConfig.o2Market + "
%c      ", "color: #6190e8;", "background: url(" + consoleConfig.gongzonghao + ") no-repeat left center;font-size: 300px;", "");
                
            }
        };
    initialize.reader();

    let NoQuery = initialize.create();
    NoQuery.prototype = {
        initialize: function () {
            return this;
        },
        /*system.js 缓存全局对象 对外公布*/
        elementSys: {
            key: variableObj.keys
        },
        /*数字判断*/
        digits: function (value) {
            return /^d+$/.test(value);
        },
        /*中文判断*/
        isChinese: function (str) {
            return /[u4E00-u9FA5]/g.test(str);
        },
        /*ajax 全局入口 支持登入是否超时、添加Token */
        ajax: function (obj) {
            var objs = $.extend({
                dataType: "json",
                data: obj.data,
                error: function (xmlHttpRequest, textStatus, errorThrown) {
                    console.error(XMLHttpRequest + "-----" + textStatus + "---" + errorThrown);
                    "".msgTips("请求数据失败,问题频繁出现请联系管理员。请重新刷新浏览器或者安F5刷新 <br>或者点击任意空白处继续");
                    console.trace();
                },
                success: obj.success,
                timeout: 6000,  //超时时间设置,单位毫秒
                type: "get",
                beforeSend: function (request) {
                    request.setRequestHeader("Authorization", variableObj.keys);
                },
                //当请求完成之后调用这个函数
                complete: function (xmlHttpRequest, status) { 
                    if (status === 'timeout') {
                        "".msgTips("请求数据时间超时6秒,问题频繁出现请联系管理员。请重新刷新浏览器或者安F5刷新 <br>或者点击任意空白处继续");
                        console.error("请求时间超时6秒 问题频繁出现请联系管理员"); 
                        console.trace();
                    }
                }
            }, obj);
            $.ajax(objs);
        },
        /*ajax回调函数成功和失败判断 true 失败 false 正常*/
        IsSuccessOk: function (json) {
            try {
                if (typeof (json) == "undefined") return true;
                if (json.Result == "-1") return true;
                if (json.total == 0 && json.rows != null) return true;
                if (json.statusCode == "300") {
                    console.error("ajax success CallBack "+json.message);
                    return true;
                }
                return false;
            } catch (e) {
                return true;
            } 
        },
        //另类的表单数据"序列化"
        GetFormParamsInfo: function ($docker) {
            var jsonModle = {};
            $docker.each(function () {
                var fieldName = $(this).attr("name");
                var fieldValue = $(this).val();
                jsonModle[fieldName] = fieldValue;
            });
            return jsonModle;
        },
        //对象转化成数组
        objConversionArr: function (obj) {
            const arr = [];
            for (let i in obj) {
                if (obj.hasOwnProperty(i)) {
                    arr.push(obj[i]); //属性
                }
            }
            return arr;
        },
        /*canvas图片懒加载  <img class="outLogin lazyload"  />
         *img class  设置lazyload , parent默认 #bodyApp  
        */
        renderCvs: function (parent ="#bodyApp", maxValue) {
            var imgList = $('.lazyload', parent);
            if (imgList.length < 1) {
                return;
            }
            var max = maxValue || imgList.length;
            for (let i = 0; i < max; i++) {
                var imgId = imgList[i].id;
                var imageCache = localStorage.getItem(imgId);
                if (imageCache) {
                    imgList[i].src = imageCache;
                    continue;
                }
                var img = new Image();
                img.index = i;
                img.id = imgId;
                img.crossorigin = "anonymous";
                img.onload = function () {
                    var _this = this;
                    var zCvs = $('#' + this.id);
                    var domCvs = zCvs[0];
                    domCvs.src = this.src;
                    zCvs.removeClass('lazyload');
                    try {
                        var cvs = document.createElement('canvas');
                        cvs.style.display = 'none';
                        document.body.appendChild(cvs);
                        var rcvs = cvs.getContext('2d');
                        cvs.width = 140;
                        cvs.height = 108;
                        rcvs.drawImage(this, 0, 0, 140, 108);
                        //toDataURL()转成base64字符串
                        setTimeout(function () {
                            var data = cvs.toDataURL();
                            localStorage.setItem(_this.id, data);
                            document.body.removeChild(cvs);
                        }, 200);
                    } catch (ex) {
                        console.error("renderCvs" + ex);
                    }
                }
                img.src = imgList[i].getAttribute('data-src');
            }
        }
    };

    /* 时间格式化(火狐特殊处理) new Date(xx).format("yyyy-MM-dd hh:mm:ss") */
    Date.prototype.format = function (format) {
        var o =
            {
                "M+": this.getMonth() + 1, //month
                "d+": this.getDate(), //day
                "h+": this.getHours(), //hour
                "m+": this.getMinutes(), //minute
                "s+": this.getSeconds(), //second
                "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
                "S": this.getMilliseconds() //millisecond
            }
        if (/(y+)/.test(format))
            format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(format))
                format = format.replace(RegExp.$1,
                    RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        return format;
    }
    //火狐时间异常
    String.prototype.replaceDate = function() {
        return this.replace(/-/g, "/");
    };
    /* 数字*100 舍入误差 rank保留的小数位 https://segmentfault.com/q/1010000005697295 Math.signFigures(0.56 * 100)*/
    Math.signFigures = function (num, rank = 6) {
        if (!num) return (0);
        const sign = num / Math.abs(num);
        const number = num * sign;
        const temp = rank - 1 - Math.floor(Math.log10(number));
        let ans;
        if (temp > 0) {
            ans = parseFloat(number.toFixed(temp));
        }
        else if (temp < 0) {
            ans = Math.round(number / Math.pow(10, temp)) * temp;
        }
        else {
            ans = Math.round(number);
        }
        return (ans * sign);
    };

    /*数组插入指定位置 */
    Array.prototype.insertExtend = function (index, value) {
        this.splice(index, 0, value);
    };
    //数组是否存在指定的key 存在的key,并返回数组、和索引
    Array.prototype.existsKey = function (key) {
        var re = null;
        for (var i = 0; i < this.length; i++) {
            if (this[i][key] != null && typeof (this[i][key]) !="undefined") {
                re = {
                    arr: this[i],
                    arrIndex: i
                }
                break;
            }
        }
        return re;
    };
    //判断是否存在指定的key 存在的key 和keyValue,并返回数组、和索引
    Array.prototype.existsNameyiShion = function (key, keyValue) {
        var re = null;
        for (var i = 0; i < this.length; i++) {
            if (this[i][key] === keyValue) {
                re = {
                    arr: this[i],
                    arrIndex: i
                }
                break;
            }
        }
        return re;
    };
    //移除数组中的某元素
    Array.prototype.removeExtend  = function (obj) {
        for (var i = 0; i < this.length; i++) {
            if (obj == this[i]) {
                this.splice(i, 1);
                break;
            }
        }
        return this;
    }

    //折线图 <canvas ></canvas>
    String.prototype.drawingLineCanvas = function (data, targetProperty) {
        const cv = document.getElementById(targetProperty.id);
        cv.width = targetProperty.width;
        cv.height = targetProperty.height;
        const maxNum = Math.max.apply(null, data);           //求数组中的最大值
        var padding = 7,                                     //边距
            arrowWidth = 7,                                  //箭头的宽度
            xLength = cv.width - 2 * padding - arrowWidth,     //x轴的长度
            yLength = cv.height - 2 * padding - arrowWidth,    //y轴的长度
            pointsWidth = xLength / (data.length + 1);       //折线上每个点之间的距离
        const ctx = cv.getContext("2d");//ctx.beginPath();//当前的点设置为 (0,0) 
        for (let i = 0; i < data.length; i++) {
            const pointX = padding + (i + 1) * pointsWidth;                       //边距+点平均距离*(i+1)
            const pointY = padding + arrowWidth + (1 - data[i] / maxNum) * yLength; //边距+(1- 值/最大值)*y坐长度(y坐长自定义长度)
            ctx.lineTo(pointX, pointY);//下一个点
        }
        ctx.strokeStyle = targetProperty.color;//css
        ctx.lineWidth = targetProperty.lineWidth;//线粗细 数字类型
        ctx.stroke(); //画线
    }
    /* 4舍5入 保留fixed小数点 整数去掉.0 */
    String.prototype.custFloats = function (value, fixed, ispercent = false) {
        if (value == null || value === "undefined") return "";
        var result = null;
        if (typeof (value) == "string") {
            if (value.indexOf(".") ===-1) {
                result = value;
            } else {
                result=  parseFloat(value).toFixed(fixed);
            }
        } else {
            if (value.toString().indexOf(".") === -1) {
                result = value;
            } else {
                result = parseFloat(value.toFixed(fixed));
            }
        }
        if (ispercent && parseFloat(value)>0) {
            result = result + "%";
        }
        return result;
    }
     /*数字每隔三位加逗号分开*/
    String.prototype.Locale = function (value) {
        if (typeof value === 'undefined' || value == null) return 0;
        const temp = Number(value);
        return temp<999 ? value : Number(value).toLocaleString();
    };
    /*设置head标题  */
    String.prototype.setHeadTitle = function (element,value) {
        document.querySelector(element).innerText = value;
    };
    /*获取url参数值 */
    String.prototype.getUrlParam = function (name) {
        const regExp = new RegExp('([?]|&)' + name + '=([^&]*)(&|$)');
        const result = variableObj.url.match(regExp);
        if (result) {
            const str = decodeURIComponent(result[2]);
            var arr = str.split('#');
            return arr.length === 2 ? arr[0] : str;
        } else {
            let msg = `url:${variableObj.url}地址,无参数 ${name} 。<br>请仔细检查4秒自动关闭窗口`;
            "".msgTips(msg,true);
            console.error(msg); 
            return null;
        }
    };
    /*信息提示 支持自定义 按esc退出 */
    String.prototype.msgTips = function (info, isClose = false) {
        variableObj.msgTipsBody.innerHTML = info;
        variableObj.msgTips.modal();
        if (isClose) {
            setTimeout(function() {
                variableObj.msgTips.modal('hide');
            },3000);
        }
    };
    /*load */
    String.prototype.loadTips = function (isshow = false) {
        var txt = ";display:none;";
        if (isshow) {
            txt = ";display:block;";
        }
        variableObj.progressBar.style = txt;
    };

    /*错误监听 */
    window.onerror = function (msg, url, l) {
        const txt = `本页中存在错误<br>
                     错误:${msg}<br> 
                     地址:${url}<br>
                     行:${l}<br>
                     点击任意空白处继续或刷新浏览器,问题频繁出现请联系管理员。`;

        "".msgTips(txt);
        console.error(txt); 
        return true;
    }
    /* 外部直 window.$sys访问或者 $sys*/
    window.$sys = new NoQuery();
  })(window);