【整理】【精华】【实用】常用代码片段

 

//替代绑定模板数据________________________

    .replace(/{形参}/g, 实参);

    html += tpl
        .replace(/{形参}/g, 实参);
//for循环________________________

    var arr =
    for (var i = 0, len = arr.length; i < len; i++) {
        var a = arr[i];

    }


    var arr =, html = '', tpl = '{形参}';
    for (var i = 0, len = arr.length; i < len; i++) {
        var a = arr[i];
        html += tpl
            .replace(/{形参}/g, 实参)
            .replace(/{形参}/g, 实参);
    }
    DOM.innerHTML = html;
//Axios读取后台数据________________________

var params = {参数名: "参数值"};
this.$axios.get("接口路径", {params: params}).then(r => {
    r = r.data;
    if (r.status == "SUCCESS") {
        r = r.data;
        if (r) {/*这里写代码*/
            /* this.items = r;*/
        }
    } else {
        alert(r.message);
    }
}).catch(e => {
    console.log("【接口报错】", e);
});
//将数字转换为保留2位有效数字的百分数________________________
    var value = 0.0251;
    value = parseFloat((value * 100).toFixed(2)) + '%';
    alert(value);
// 当前日期转换为:yyyy/MM/dd HH:mm:ss(24小时制)________________________
new Date().toLocaleString("zh-Hans-CN", {dateStyle: "short", timeStyle: "medium", hour12: false});

// 当前日期转换为:yyyy/MM/dd 上午/下午HH:mm:ss(12小时制)________________________
new Date().toLocaleString("zh-Hans-CN", {dateStyle: "short", timeStyle: "medium"});

// 当前日期转换为:yyyy-MM-dd HH:mm:ss(24小时制 双位数)________________________
new Date().toLocaleString("zh-Hans-CN", {year: "numeric", month: "2-digit", day: "2-digit", hour12: false, hour: "2-digit", minute: "2-digit", second: "2-digit"}).replace(/\//g, "-");

// 当前日期转换为:yyyy-MM-dd________________________
new Date().toLocaleString("zh-Hans-CN", {year: "numeric", month: "2-digit", day: "2-digit"}).replace(/\//g, "-");

// 当前日期转换为:HH:mm:ss(24小时制 双位数)________________________
new Date().toLocaleString("zh-Hans-CN", {hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false});

// 当前日期转换为:HH:mm(24小时制 双位数)________________________
new Date().toLocaleString("zh-Hans-CN", {hour: "2-digit", minute: "2-digit", hour12: false});

// 当前日期转换为:公元yyyy年MM月dd日星期D HH:mm:ss(24小时制)________________________
new Date().toLocaleString("zh-Hans-CN", {era:'short',year: "numeric", month: "short", day: "numeric", weekday: "long", hour: "numeric", minute: "numeric", second: "numeric", hour12: false});

// 当前日期转换为:yyyy年MM月dd日星期D HH:mm:ss(24小时制)________________________
new Date().toLocaleString("zh-Hans-CN", {year: "numeric", month: "short", day: "numeric", weekday: "long", hour: "numeric", minute: "numeric", second: "numeric", hour12: false});

// 当前日期转换为:yyyy年MM月dd日周D HH:mm:ss(24小时制)________________________
new Date().toLocaleString("zh-Hans-CN", {year: "numeric", month: "short", day: "numeric", weekday: "short", hour: "numeric", minute: "numeric", second: "numeric", hour12: false});

// 当前日期转换为:yyyy年MM月dd日D HH:mm:ss(24小时制)________________________
new Date().toLocaleString("zh-Hans-CN", {year: "numeric", month: "short", day: "numeric", weekday: "narrow", hour: "numeric", minute: "numeric", second: "numeric", hour12: false});

// 当前日期转换为:yyyy年MM月dd日星期D HH:mm:ss(24小时制)________________________
new Date().toLocaleString("zh-Hans-CN", {year: "numeric", month: "short", day: "numeric", hour: "numeric", minute: "numeric", second: "numeric", hour12: false});

// 当前日期转换为:yyyy年MM月dd日星期D________________________
new Date().toLocaleString("zh-Hans-CN", {year: "numeric", month: "short", day: "numeric", weekday: "long"});

// 当前日期转换为:yyyy年MM月dd日周D________________________
new Date().toLocaleString("zh-Hans-CN", {year: "numeric", month: "short", day: "numeric", weekday: "short"});

// 当前日期转换为:yyyy年MM月dd日D________________________
new Date().toLocaleString("zh-Hans-CN", {year: "numeric", month: "short", day: "numeric", weekday: "narrow"});

// 当前日期转换为:yyyy年MM月dd日________________________
new Date().toLocaleString("zh-Hans-CN", {year: "numeric", month: "short", day: "numeric"});

//部分笨拙的方法________________________
var yearMonthDay = new Date().getFullYear() + ("0" + (new Date().getMonth() + 1)).slice(-2) + ("0" + new Date().getDate()).slice(-2);//yyyyMMdd
var year_Month_Day = new Date().getFullYear() + "-" + ("0" + (new Date().getMonth() + 1)).slice(-2) + "-" + ("0" + new Date().getDate()).slice(-2);//yyyy-MM-dd

//当月第一天、当月最后一天年月日(yyyy-MM-dd)________________________
new Date(new Date().getFullYear(),new Date().getMonth(),1).toLocaleString("zh-Hans-CN", {year: "numeric", month: "2-digit", day: "2-digit"}).replace(/\//g, "-");
new Date(new Date().getFullYear(),new Date().getMonth()+1,0).toLocaleString("zh-Hans-CN", {year: "numeric", month: "2-digit", day: "2-digit"}).replace(/\//g, "-");

/**日期方法大合集*/
var date = {
        //新方法(时:分:秒)
        HH_mm_ss(date = null) {
            return new Date(date).toLocaleString("zh-Hans-CN", { hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false });
        },
        //新方法(年-月-日)
        yyyy_MM_dd(date = null) {
            return new Date(date).toLocaleString("zh-Hans-CN", { year: "numeric", month: "2-digit", day: "2-digit" }).replace(/\//g, "-");
        },
        //新方法(年-月-日 时:分:秒)
        yyyy_MM_dd_HH_mm_ss(date = null) {
            return new Date(date).toLocaleString("zh-Hans-CN", { year: "numeric", month: "2-digit", day: "2-digit", hour12: false, hour: "2-digit", minute: "2-digit", second: "2-digit" }).replace(/\//g, "-");
        },
    yearMonthDay: function () {
        return new Date().getFullYear() + ("0" + (new Date().getMonth() + 1)).slice(-2) + ("0" + new Date().getDate()).slice(-2);
    }, year_Month_Day: function () {
        return new Date().getFullYear() + "-" + ("0" + (new Date().getMonth() + 1)).slice(-2) + "-" + ("0" + new Date().getDate()).slice(-2);
    }, yMd: function (dt, split) {
        dt || (dt = new Date());
        split || (split = "-");
        return dt.getFullYear() + split + ("0" + (dt.getMonth() + 1)).slice(-2) + split + ("0" + dt.getDate()).slice(-2);
    },
    /**判断是否逾期*/
    over: function (endDate, isEqual) {
        var d1 = new Date().getTime(), d2 = new Date(endDate).getTime();
        return isEqual ? d1 >= d2 : d1 > d2;
    },
    /**比较日期大小,前一个日期大于(isEqual=true时 比较大于等于)后一个日期时返回true*/
    compare: function (d1, d2, isEqual) {
        d1 = new Date(d1).getTime(), d2 = new Date(d2).getTime();
        return isEqual ? d1 >= d2 : d1 > d2;
    },
    /**获取指定日期之前/之后的某天*/
    pointDate: function (dt, n) {
        if (!n) return dt;
        var s = "/";
        if (dt.indexOf("-") > -1) {
            s = "-", dt = dt.replace(/-/g, "/");
        } else if (dt.indexOf(".") > -1) {
            s = ".", dt = dt.replace(/\./g, "/");
        }
        var d = new Date(dt), lw = new Date(Number(d) + 1000 * 60 * 60 * 24 * Math.floor(n)), /*n天数*/ ly = lw.getFullYear(), lm = lw.getMonth() + 1, ld = lw.getDate(), sd = ly + s + (lm < 10 ? "0" + lm : lm) + s + (ld < 10 ? "0" + ld : ld);
        return sd;
    },
    /**获得当前日期之前之后任意天的日期*/
    anyDate: function (n) {
        var dt = new Date();
        dt.setDate(dt.getDate() + n);
        return date.yMd(dt);
    },
    /**获得当前日期之前之后任意天的日期+时间*/
    anyDateTime: function (n) {
        var dt = new Date();
        dt.setDate(dt.getDate() + n);
        return formatDateTime(dt);
    },
    /**获得任意天的日期时间戳:n为负数就是过去的天数,正数则为未来的天数*/
    anyDateTimeStamp: function (n) {
        return new Date(date.anyDate(n) + " 00:00:00").getTime();
    },
    /**获得本月的开始日期、结束日期*/
    monthStartOrEndDate: function (isStart) {
        var now = new Date(), m = now.getMonth(), y = now.getFullYear(), msd = new Date(y, m, Boolean(isStart) ? 1 : new Date(y, m + 1, 0).getDate());
        return date.yMd(msd);
    },
    /**获得本周的开始日期、结束日期*/
    weekStartOrEndDate: function (isStart) {
        var now = new Date(), d = now.getDay(), nd = now.getDate(), m = now.getMonth(), y = now.getFullYear(), wsd = new Date(y, m, nd + (Boolean(isStart) ? -d : 6 - d));
        return date.yMd(wsd);
    },
    /**计算指定日期加上多少天、加多少月、加多少年的日期*/
    add: function (type, number, date) {
        var d = date ? (date instanceof Date ? date : new Date(date)) : new Date();
        switch (type) {
            case "y":
                d.setFullYear(d.getFullYear() + number);
                return d;
            case "q":
                d.setMonth(d.getMonth() + number * 3);
                return d;
            case "m":
                d.setMonth(d.getMonth() + number);
                return d;
            case "w":
                d.setDate(d.getDate() + number * 7);
                return d;
            case "d":
                d.setDate(d.getDate() + number);
                return d;
            case "h":
                d.setHours(d.getHours() + number);
                return d;
            case "m":
                d.setMinutes(d.getMinutes() + number);
                return d;
            case "s":
                d.setSeconds(d.getSeconds() + number);
                return d;
            default:
                d.setDate(d.getDate() + number);
                return d;
        }
        /*/!* 加2天.*!/ alert(date.add("d ", 2).toLocaleString()) /!* 加2月.*!/ alert(date.add("m ", 2).toLocaleString()) /!* 加2年*!/ alert(date.add("y ", 2).toLocaleString());*/
    },
    format: function (date, fmt) {
        date = date instanceof Date ? date : new Date(date);
        var o = {
            "M+": date.getMonth() + 1,
            "d+": date.getDate(),
            "h+": date.getHours() % 12 == 0 ? 12 : date.getHours() % 12,
            "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));
        }
        if (/(E+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "星期" : "周") : "") + "日一二三四五六".charAt(date.getDay()));
        }
        for (var 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;
    },
    /**格式化日期:yyyy-MM-dd HH:mm:ss */
    formatDate: function (timeStamp) {
        return date.format(timeStamp ? (timeStamp instanceof Date ? timeStamp : new Date(timeStamp)) : new Date(), "yyyy-MM-dd");
    },
    /**格式化日期:yyyy-MM-dd HH:mm:ss */
    formatDateTime: function (timeStamp) {
        return date.format(timeStamp ? (timeStamp instanceof Date ? timeStamp : new Date(timeStamp)) : new Date(), "yyyy-MM-dd HH:mm:ss");
    },
    /**格式化日期:yyyy年MM月dd日 HH:mm:ss */
    formatToyyyyMMddHHmmssEE: function (timeStamp) {
        return date.format(timeStamp ? (timeStamp instanceof Date ? timeStamp : new Date(timeStamp)) : new Date(), "yyyy年MM月dd日 HH:mm:ss EE");
    }, getDay: function () {
        return "星期" + "日一二三四五六".charAt(new Date().getDay());
    },
    /**转换Date为24小时计时时间格式*/
    to24hours: function (date) {
        var now = date ? (date instanceof Date ? date : new Date(date)) : new Date(), now = now.toLocaleTimeString("zh-Hans-CN", {hour12: false}), now = now.substr(0, now.lastIndexOf(":"));
        return now;
    },
    /**将秒数量转换为时分秒字符串*/
    toHourMinuteSecond: function (second, data) {
        var t = "",
            s = Math.round(second),
            d = data.isDoubleDigits,//显示双位数
            hz = data.hideZero,//隐藏为0的时间单位
            hh = data.hideHour,//隐藏小时
            hm = data.hideMinute,//隐藏分钟
            hs = data.hideSecond;//隐藏秒钟
        if (s > 0) {
            var hour = Math.floor(s / 3600), min = Math.floor(s / 60) % 60, sec = s % 60;
            hh || (hz && !hour) || (d && hour < 10 && (t += "0"), t += hour + "时");
            hm || (hz && !min) || (d && min < 10 && (t += "0"), t += min + "分");
            hs || (hz && !sec) || (d && sec < 10 && (t += "0"), t += sec + "秒");
        }
        return t;
        //测试用例
        /*alert(toHourMinuteSecond(3661,{
            // isDoubleDigits:true,
            hideZero:true,
            // hideHour:true,
            // hideMinute:true,
            // hideSecond:true,
        }));*/
    },
    /**获取最近几个月的年月份*/
    getRecentSeveralMonth: function (n) {
        var date = new Date();
        var nearMonth = [];
        for (var i = 1; i <= n; i++) {
            date.setMonth(date.getMonth() - 1);
            nearMonth.unshift(date.getFullYear() + "/" + (date.getMonth() + 1));
        }
        return nearMonth;
    },
    /**把时间转换为分钟数*/
    hourMinuteToMinute: function (timeString) {
        timeString = timeString.replace(/:/g, ":").replace(/\ |\ /g, "").replace(/::/g, ":").split(":");
        return parseInt(timeString[0] * 60) + parseInt(timeString[1]);
    },
    /**显示几分钟前刚刚发布文章*/
    timeAgo: function (timeStamp) {
        var minute = 1000 * 60, hour = minute * 60, day = hour * 24, week = day * 7, month = day * 30, now = new Date().getTime(), diffValue = now - timeStamp;
        var minC = diffValue / minute, hourC = diffValue / hour, dayC = diffValue / day, weekC = diffValue / week, monthC = diffValue / month, res;
        if (monthC > 3 && monthC < 12) {
            res = "半年前";
        } else if (monthC >= 1 && monthC <= 3) {
            res = parseInt(monthC) + "月前";
        } else if (weekC >= 1 && weekC < 4) {
            res = parseInt(weekC) + "周前";
        } else if (dayC >= 1 && dayC < 7) {
            res = parseInt(dayC) + "天前";
        } else if (hourC >= 1 && hourC < 24) {
            res = parseInt(hourC) + "小时前";
        } else if (minC >= 1 && minC < 60) {
            res = parseInt(minC) + "分钟前";
        } else if (diffValue >= 0 && diffValue <= minute) {
            res = "刚刚";
        } else {
            res = this.formatDateTime(timeStamp);
        }
        return res;
    }, between: function (startDate, endDate) {
        startDate = startDate instanceof Date ? startDate : new Date(startDate);
        endDate = endDate instanceof Date ? endDate : new Date(endDate);
        var today = new Date().getTime(), startDate = new Date(startDate).getTime(), endDate = new Date(endDate).getTime();
        return startDate < today && today < endDate;
    },
    /**计算两个日期相差天数*/
    getDayBetween: function (startDate, endDate) {
        startDate = startDate instanceof Date ? startDate : new Date(startDate);
        endDate = endDate instanceof Date ? endDate : new Date(endDate);
        return Math.floor(this.getMillisecondBetween(startDate, endDate));
    },
    /**计算两个日期相差毫秒数*/
    getMillisecondBetween: function (startDate, endDate) {
        startDate = startDate instanceof Date ? startDate : new Date(startDate);
        endDate = endDate instanceof Date ? endDate : new Date(endDate);
        return Math.abs((Date.parse(endDate) - Date.parse(startDate)) / 86400000);
    }
};
/*验证用户名输入*/
    onkeyup = "this.value=this.value.replace(/\ |\ |[^\x00-\x80]/g,'')"
//自定义控制台显示样式________________________
    var msg = '提内内容';
    console.log('%c报错信息:','background:red;color:white;padding:5px;border-radius:5px;',msg);
//Vue常用读取后台接口方法________________________
    var params = {参数名: "参数值"};
    this.$axios.get("接口路径", {params: params}).then(r => {
        r = r.data;
        if (r.status == "SUCCESS") {
            r = r.data;
            if (r) {/*这里写代码*/
                /* this.items = r;*/
            }
        } else {
            console.log('%c报错信息', 'background:red;color:white;padding:5px;border-radius:5px;',r.message);
        }
    }).catch(e => {
        console.log("【接口报错】", e);
    });
/**验证一切*/function checkEverything(type, s) {
    switch (type.toString().toLocaleLowerCase()) {
        case "postcode": /**验证邮政编码*/
            return /^(0[1234567]|1[012356]|2[01234567]|3[0123456]|4[01234567]|5[1234567]|6[1234567]|7[012345]|8[013456])\d{4}$/.test(s);
        case "uppercase": /**验证是否包含大写字母*/
            return /[A-Z]/.test(s);
        case "car":
            s = s.toString();
            if (s.length == 8) {
                return /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DF]$)|([DF][A-HJ-NP-Z0-9][0-9]{4}$))/.test(s);
            } else if (s.length == 7) {
                return /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1}$/.test(s);
            } else {
                return false;
            }
        case "integer":
            return /^[0-9]+$/.test(s);
        case "special":
            return /[\<\>]/.test(s);
        case "name":/*中文名*/
            return /^[\u4E00-\u9FA5\uf900-\ufa2d·s]{2,20}$/.test(s);
        case "cn":/*包含中文*/
            return /[\u4E00-\u9FA5]/i.test(s);
        case "id":/*身份证*/
            return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(s);
        case "user": /*账号*/
            return /^[a-zA-z]\w{3,15}$/.test(s);
        case "httpurl":
            return /(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(s);
        case "url":
            return /^(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])+$/.test(s);
        case "mobile": /*手机号*/
            return /^1\d{10}$/.test(s);
        case "tel": /*座机号*/
            return /^0\d{2,3}-?\d{7,8}$/.test(s);
        case "email":
            return /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(s);
        case "number":
            return /^\d+$/g.test(s);
        case "password":
            if (s == "") {
                return false;
            } else if (s.split(" ").length != 1) {
                return false;
            } else {
                if ((s.search(/^[a-zA-Z]+$/g) != -1) || (s.search(/^[0-9]+$/g) != -1)) {
                    return false;
                } else if (s.search(/^[a-zA-Z0-9]+$/g) != -1) {
                    return false;
                } else {
                    return false;
                }
            }
            return true;
    }
}
/**表单验证神器1.0*/ var vd = {
        a: function (arr) { /** arr 结构说明: [{ input:"[必填]输入框控件的class or id",(需要特别说明,每个输入框文件都需要加入placeholder) type:"[可选]验证的格式类型(例如:name中文姓名|id身份证|mobile移动手机好(具体去舒工写的checkEverything方法查看))", focus:"[可选]需要聚焦高亮闪烁显示的元素DOM(注意是DOM!!!)(依赖舒工的focusDOM类)", tip:"[可选]当用户输入内容验证失败时候弹出提示框(注意!如果加入了此参数,需要引入layer-ui的离线包,下载地址https://www.layui.com/)", },] */
            for (var i = 0, len = arr.length; i < len; i++) {
                var a = arr[i], input = document.querySelector(a.input), focus = a.focus, type = a.type, tip = a.tip;
                if (!a.input) return console.log("vd.a方法的arr参数的input属性为空");
                var value = input.value.replace(/\ |\ /g, "");
                focus || (focus = input);
                if (!value) {
                    console.log(focus);
                    var txt = "输入不能为空";
                    input.value = "", input.placeholder = input.placeholder || txt;
                    focusDOM.to(focus, input);
                    tip && layer.msg(txt);
                    return true
                }
                if (type && !checkEverything(type, value)) {
                    input.value = "", input.placeholder = tip || input.placeholder;
                    tip && layer.msg(tip);
                    focusDOM.to(focus, input);
                    return true
                }
            }
            return false;
        }
    };
    /*测试用例*/
    document.querySelector("form").onsubmit = function () {
        if (vd.a([{input: "#a1", type: "name", focus: document.querySelector("#a1").parentNode,}, {input: "#a2", type: "id", focus: document.querySelector("#a2").parentNode, tip: "您输入的身份证格式不正确",},])) return false;
        return false;
    };
    .shadow {
        /*穿透阴影效果兼容各种浏览器*/
        -webkit-filter: drop-shadow(5px 10px 20px rgba(0, 0, 0, .5));
        filter: drop-shadow(5px 10px 20px rgba(0, 0, 0, .5));
        -ms-filter: "progid:DXImageTransform.Microsoft.Dropshadow(OffX=5, OffY=10, Color='#CCC')";
        filter: "progid:DXImageTransform.Microsoft.Dropshadow(OffX=5, OffY=10, Color='#CCC')";
    }

    @media screen and (max-width: 1260px) {
        .div {
            /**适应1280x800的屏幕,除去浏览器滚动条宽度20px*/
        }
    }
    @media screen and (min-width: 1261px) and  (max-width: 1346px) {
        .div {
            /**适应1366x768的屏幕,除去浏览器滚动条宽度20px*/
        }
    }
    @media screen and (min-width: 1347px) and  (max-width: 1420px) {
        .div {
            /**适应1440x900的屏幕,除去浏览器滚动条宽度20px*/
        }
    }
    @media screen and (min-width: 1421px) and  (max-width: 1900px) {
        .div {
            /**适应1920x1080的屏幕,除去浏览器滚动条宽度20px*/
        }
    }
    @media screen and (min-width: 1901px) {
        .div {
            /**适应宽度超过1920的屏幕,除去浏览器滚动条宽度20px*/
        }
    }
    @media screen and (max-height: 668px) {
        .div {
            /**适应1366x768的屏幕,除去浏览器菜单栏、标签栏、状态栏以及系统任务栏高度100px*/
        }
    }
    @media screen and (min-height: 669px) and  (max-height: 800px) {
        .div {
            /**适应1440x900的屏幕,除去浏览器菜单栏、标签栏、状态栏以及系统任务栏高度100px*/
        }
    }
    @media screen and (min-height: 801px) and  (max-height: 980px) {
        .div {
            /**适应1920x1080的屏幕,除去浏览器菜单栏、标签栏、状态栏以及系统任务栏高度100px*/
        }
    }
    @media screen and (min-height: 981px) {
        .div {
            /**适应高度超过1080的屏幕,除去浏览器菜单栏、标签栏、状态栏以及系统任务栏高度100px*/
        }
    }
    
    
 /**禁止拖拽保存图片*/function donotDrag() {
        window.ondragstart = window.ontouchmove = document.ondragstart = document.ontouchmove = function (e) {
            e.preventDefault();
            return false;
        };
    }



$(function(){

})

$().ready(function(){

})

$(document).ready(function(){

})

$(window).load(function(){

})
.animate-name {
    animation: animate-name .618s linear infinite;
    -moz-animation: animate-name .618s linear infinite; /** Firefox */
    -webkit-animation: animate-name .618s linear infinite; /** Safari 和 Chrome */
    -o-animation: animate-name .618s linear infinite; /** Opera */
}

@keyframes animate-name {
    0% {
        transform: rotate(0deg);
    }
    50% {
        transform: rotate(180deg);
    }
    100% {
        transform: rotate(360deg);
    }
}

@-moz-keyframes animate-name {
    0% {
        -moz-transform: rotate(0deg);
    }
    50% {
        -moz-transform: rotate(180deg);
    }
    100% {
        -moz-transform: rotate(360deg);
    }
}

@-webkit-keyframes animate-name {
    0% {
        -webkit-transform: rotate(0deg);
    }
    50% {
        -webkit-transform: rotate(180deg);
    }
    100% {
        -webkit-transform: rotate(360deg);
    }
}

@-ms-keyframes animate-name {
    0% {
        -ms-transform: rotate(0deg);
    }
    50% {
        -ms-transform: rotate(180deg);
    }
    100% {
        -ms-transform: rotate(360deg);
    }
}

@-o-keyframes animate-name {
    0% {
        -o-transform: rotate(0deg);
    }
    50% {
        -o-transform: rotate(180deg);
    }
    100% {
        -o-transform: rotate(360deg);
    }
}
    div {
        -webkit-transform: translateY(-5px); /* for Chrome || Safari */
        -moz-transform: translateY(-5px); /* for Firefox */
        -ms-transform: translateY(-5px); /* for IE */
        -o-transform: translateY(-5px); /* for Opera */
        transform: translateY(-5px);
    }
    *:not([class*=layui-layer]), :before, :after, :visited, :focus, :focus-within, :checked {
        transition: .382s; /** IE 9 */
        -moz-transition: .382s; /** Firefox 4 */
        -webkit-transition: .382s; /** Safari 和 Chrome */
        -o-transition: .382s;
        /** Opera */
        -khtml-transition: .382s; /** only Safari */
    }
div {
        transition: .382s;
        -moz-transition: .382s;
        -webkit-transition: .382s;
        -o-transition: .382s;
        -khtml-transition: .382s;
    }
    /*自定义选择内容样式*/
    ::selection {
        background: rgba(82, 170, 255, .3);
        color: #2366bd;
    }

    ::-moz-selection {
        background: rgba(82, 170, 255, .3);
        color: #2366bd;
    }

    ::-webkit-selection {
        background: rgba(82, 170, 255, .3);
        color: #2366bd;
    }
/*滚动条轨道*/
    ::-webkit-scrollbar {
        width: 8px;
        background: rgba(255, 255, 255, 0.2);
    }

    /*滚动条滑块*/
    ::-webkit-scrollbar-thumb {
        border-radius: 8px;
        background: rgba(255, 255, 255, 0.2);
    }

    /*移入滑块*/
    ::-webkit-scrollbar-thumb:hover {
        background: rgba(255, 255, 255, 0.4);
    }
    var url = "http://www.shuzhiqiang.com/api";
    var data = {start: 0, count: 1};
    $.ajax({
        type: "POST", url: url, data: data, success: function (data) {
            if (data.code == 200) {
                console.log(data);
                document.write(JSON.stringify(data));
            }
            else {
                console.log("报错", data);
            }
        }, error: function (e) {
            console.log(e);
        }
    });
    $.ajax({
        type: "GET", url: "http://www.shuzhiqiang.com/api", data: {username: "admin", password: "123456"}, success: function (data) {
            document.write(JSON.stringify(data));
        }, error: function (e) {
            console.log(e);
        }
    })
/**jsonp方式获取数据*/
    $.ajax({
        type: "POST",
        url: "http://www.shuzhiqiang.com/api",
        data: {method: "originateCollectByDay", startDate: "2017-05-01", endDate: "2017-07-01"},
        dataType: "jsonp",
        jsonp: 'callback',
        success: function (data) {
            alert(data[0].originate);
        }
    })


    /**postJSON自定义方法*/
    var postJSON = function (url, data, success) {
        typeof  data == "function" && (success = data, data = {});
        typeof  data == "undefined" || typeof data == "null" && (success = function () {
        }, data = {});
        return $.ajax({
            type: "POST",
            contentType:
                "application/x-www-form-urlencoded;application/json; charset=utf-8",
            /**这个里面的application/x-www-form-urlencoded如果去掉,Tomcat的HttpServletRequest类request.getParameter(name)将无法获取数据*/ dataType: "jsonp",
            jsonp: "callback",
            url: url,
            data: data,
            success:
            success
        });
    };
    /**调用postJSON*/$.postJSON("http://www.shuzhiqiang.com/api", {username: "admin", password: "123456"}, function (data) {
        console.log(data);
    });

/*径向渐变合集----------------------------------------------------------------*/

/* closest-side */
    .closest-side .circle {
        background-image: -webkit-radial-gradient(closest-side circle at 50% 90%, transparent, black);
        background-image: -o-radial-gradient(closest-side circle at 50% 90%, transparent, black);
        background-image: -moz-radial-gradient(closest-side circle at 50% 90%, transparent, black);
        background-image: radial-gradient(closest-side circle at 50% 90%, transparent, black);
    }

    .closest-side .ellipse {
        background-image: -webkit-radial-gradient(closest-side ellipse at 50% 90%, transparent, black);
        background-image: -o-radial-gradient(closest-side ellipse at 50% 90%, transparent, black);
        background-image: -moz-radial-gradient(closest-side ellipse at 50% 90%, transparent, black);
        background-image: radial-gradient(closest-side ellipse at 50% 90%, transparent, black);
    }

    /* closest-corner */
    .closest-corner .circle {
        background-image: -webkit-radial-gradient(closest-corner circle at 50% 90%, transparent, black);
        background-image: -o-radial-gradient(closest-corner circle at 50% 90%, transparent, black);
        background-image: -moz-radial-gradient(closest-corner circle at 50% 90%, transparent, black);
        background-image: radial-gradient(closest-corner circle at 50% 90%, transparent, black);
    }

    .closest-corner .ellipse {
        background-image: -webkit-radial-gradient(closest-corner at 50% 90%, transparent, black);
        background-image: -o-radial-gradient(closest-corner at 50% 90%, transparent, black);
        background-image: -moz-radial-gradient(closest-corner at 50% 90%, transparent, black);
        background-image: radial-gradient(closest-corner ellipse at 50% 90%, transparent, black);
    }

    /* farthest-side */
    .farthest-side .circle {
        background-image: -webkit-radial-gradient(farthest-side circle at 50% 90%, transparent, black);
        background-image: -o-radial-gradient(farthest-side circle at 50% 90%, transparent, black);
        background-image: -moz-radial-gradient(farthest-side circle at 50% 90%, transparent, black);
        background-image: radial-gradient(farthest-side circle at 50% 90%, transparent, black);
    }

    .farthest-side .ellipse {
        background-image: -webkit-radial-gradient(farthest-side ellipse at 50% 90%, transparent, black);
        background-image: -o-radial-gradient(farthest-side ellipse at 50% 90%, transparent, black);
        background-image: -moz-radial-gradient(farthest-side ellipse at 50% 90%, transparent, black);
        background-image: radial-gradient(farthest-side ellipse at 50% 90%, transparent, black);
    }

    /* farthest-corner */
    .farthest-corner .circle {
        background-image: -webkit-radial-gradient(farthest-corner circle at 50% 90%, transparent, black);
        background-image: -o-radial-gradient(farthest-corner circle at 50% 90%, transparent, black);
        background-image: -moz-radial-gradient(farthest-corner circle at 50% 90%, transparent, black);
        background-image: radial-gradient(farthest-corner circle at 50% 90%, transparent, black);
    }

    .farthest-corner .ellipse {
        background-image: -webkit-radial-gradient(farthest-corner ellipse at 50% 90%, transparent, black);
        background-image: -o-radial-gradient(farthest-corner ellipse at 50% 90%, transparent, black);
        background-image: -moz-radial-gradient(farthest-corner ellipse at 50% 90%, transparent, black);
        background-image: radial-gradient(farthest-corner ellipse at 50% 90%, transparent, black);
    }



var browser = {
        /**浏览器可视区域宽度高度(不含纵向滚动条宽度和水平滚动条高度)*/ visibleWidth: function () {
            return document.documentElement.clientWidth || document.body.clientWidth
        }, visibleHeight: function () {
            return document.documentElement.clientHeight || document.body.clientHeight
        }, update: function () {
            /**升级浏览器*/ var s = this.version(), b = s.browser, v = s.version.split('.')[0], a = function () {
                alert('朋友!\n您还在用大家都抛弃了的浏览器版本吗?\n淘宝都不支持这个浏览器了!\n还是点击确定更新下吧!\n与世界接轨很有必要!\n祝您早日富可敌国!');
                location.replace("https://down.360safe.com/se/360se_setup.exe");
            };
            b == "chrome" && v < 55 && a();
            b == "firefox" && v < 60 && a();
            b == "msie" && v < 10 && a();
            b == "opera" && v < 55 && a();
            /*document.write(b + "的版本是" + s.version);*/
        }, version: function () {
            /**获取浏览器版本*/ var s = {}, m = navigator.userAgent.toLocaleLowerCase().match(/(msie|firefox|chrome|opera|version).*?([\d.]+)/);
            s.browser = m[1].replace(/version/, "'safari"), s.version = m[2];
            return s;
        }
    };
    /*测试用例*/
    broswer.update();




    
    
    








微信浏览器的UserAgent


Mozilla/5.0 (Linux; Android 8.0; MI 6 Build/OPR1.170623.027; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/6.2 TBS/044203 Mobile Safari/537.36 MicroMessenger/6.6.7.1321(0x26060739) NetType/WIFI Language/zh_CN

    /**原生JS实现jQuery的ready方法*/ function ready(fn) {
        var d = document;
        if (d.addEventListener) {/*标准浏览器*/
            d.addEventListener('DOMContentLoaded', function () {/*注销事件,避免反复触发*/
                d.removeEventListener('DOMContentLoaded', arguments.callee, false);
                /*执行函数*/
                fn();
            }, false);
        } else if (d.attachEvent) {/*IE浏览器*/
            d.attachEvent('onreadystatechange', function () {
                if (d.readyState == 'complete') {
                    d.detachEvent('onreadystatechange', arguments.callee);
                    /*执行函数*/
                    fn();
                }
            });
        }
    }

    /*测试用例*/
    ready(function () {
        alert("在加载完DOM(不包含图片等非文字媒体文件)之后,onload之前执行!")
    })

    var scroll = {
        id: null, scrollTop: function () {
            return document.body.scrollTop || document.documentElement.scrollTop || window.pageYOffset || 0;
        }, width: function () {
            var d = document.createElement('div'), s = {width: '100px', height: '100px', overflowY: 'scroll'}, i, w;
            for (i in s) d.style[i] = s[i];
            document.body.append(d), w = d.offsetWidth - d.clientWidth, d.remove();
            return w;
        }, twTo: function (y) { /*
$g.$utils.json = {
    /**判断JSON格式*/ isJSON: function (str) {
        if (typeof str == "string") {
            try {
                var obj = JSON.parse(str);
                if (typeof obj == "object" && obj) {
                    return true;
                } else {
                    return false;
                }
            } catch (e) {
                return false;
            }
        } else if (typeof str == "object") {
            return Object.prototype.toString.call(obj).toLocaleLowerCase() == "[object object]" && !obj.length;
        }
        return false;
    }, /**合并string类型的json*/ mergeJsonString: function () {
        return JSON.parse((jsonStr1 + jsonStr2).replace(/}{/g, ","));
    }, /**拼接两个json*/ mergeJsonObject: function (json1, json2) {
        for (var i in json1) {
            json2[i] = json1[i];
        }
        return json2;
    }, /**将JSON对象转换为字符串*//** param 将要转为URL参数字符串的对象,key URL参数字符串的前缀, encode true/false 是否进行URL编码 默认为true return URL参数字符串,index不需要传参*/ toGetString: function (param, key, encode, index) {
        index || (index = 0);
        index++;
        if (param == null) return;
        var ps = "";
        var t = typeof (param);
        if (t == "string" || t == "number" || t == "boolean") {
            ps += "&" + key + "=" + ((encode == null || encode) ? encodeURIComponent(param) : param);
        } else {
            for (var i in param) {
                var k = key == null ? i : key + (param instanceof Array ? "[" + i + "]" : "." + i);
                ps += json.toGetString(param[i], k, encode, index);
            }
        }
        index == 1 && (ps = ps.replace("&", ""));
        return ps;
        /*测试用例*/
        /* var obj = {a: '1', 'b': {c: '3'}, d: [{e: '4'}]}; alert(json.toGetString(obj)); alert(json.toGetString(obj, 'CLASS'));*/
    }, /**JSON转GET请求参数(只针对包含一个层级的json格式)*/ toGetStringForOneDepthLevel: function (json) {
        return JSON.stringify(json).replace(/\t|\n|\r|\"|\{|\}/g, "").replace(/,/g, "&").replace(/:/g, "=");
    }, /**GET请求参数转JSON(只针对包含一个层级的json格式)*/ fromGetStringForOneDepthLevel: function (getString) {
        return JSON.parse("{\"" + getString.substr(1 + getString.indexOf("?")).replace(/&/g, "\",\"").replace(/=/g, "\":\"") + "\"}");
    }, /**格式化json字符串格式*/string: function (json) {
        return JSON.stringify(json, null, 4);
    }, /**获取json对象一级属性个数*/ length: function (obj) {
        var count = 0;
        for (var i in obj) {
            count++;
        }
        return count;
    },
    //比较两个json是否相同
    isObj(object) {
        return object && typeof (object) == "object" && Object.prototype.toString.call(object).toLowerCase() == "[object object]";
    },
    isArray(object) {
        return object && typeof (object) == "object" && object.constructor == Array;
    },
    getLength(object) {
        var count = 0;
        for (var i in object) count++;
        return count;
    },
    compare(objA, objB) {
        if (!this.isObj(objA) || !this.isObj(objB)) return false; //判断类型是否正确
        if (this.getLength(objA) != this.getLength(objB)) return false; //判断长度是否一致
        return this.compareObj(objA, objB, true);//默认为true
    },
    compareObj(objA, objB, flag) {
        for (var key in objA) {
            if (!flag) //跳出整个循环
                break;
            if (!objB.hasOwnProperty(key)) {
                flag = false;
                break;
            }
            if (!this.isArray(objA[key])) { //子级不是数组时,比较属性值
                if (objB[key] != objA[key]) {
                    flag = false;
                    break;
                }
            } else {
                if (!this.isArray(objB[key])) {
                    flag = false;
                    break;
                }
                var oA = objA[key], oB = objB[key];
                if (oA.length != oB.length) {
                    flag = false;
                    break;
                }
                for (var k in oA) {
                    if (!flag) //这里跳出循环是为了不让递归继续
                        break;
                    flag = this.compareObj(oA[k], oB[k], flag);
                }
            }
        }
        return flag;
    }
};

    /**原生Ajax*/ function ajax() {
        var a = arguments[0];
        var d = {
            t: a.type || "GET", u: a.url || "", a: a.async || "true", d: a.data || null, dt: a.dataType || "text", ct: a.contentType || "application/x-www-form-urlencoded", b: a.beforeSend || function () {
            }, s: a.success || function () {
            }, e: a.error || function () {
            }
        };
        d.b();
        var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
        xhr.responseType = d.dt;
        xhr.open(d.t, d.u, d.a);
        xhr.setRequestHeader("Content-Type", d.ct);
        xhr.send(JSON.stringify(d.d).replace(/\t|\n|\r|\"|\{|\}/g, "").replace(/,/g, "&").replace(/:/g, "="));
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    d.s(xhr.response)
                } else {
                    d.e()
                }
            }
        }
    };
    /*测试用例*/
    ajax({
        type: "POST", url: "http://www.shuzhiqiang.com/api", dataType: "json", data: {start: 0, count: 5}, beforeSend: function (e) {
            console.log("开始加载…");
        }, success: function (msg) {
            console.log(msg)
        }, error: function (e) {
            console.log(e)
        }
    })

    /**路径修复:因更换服务器图片路径指向错误的问题*/ var pathRepair = {
        __r: function (p, o, n) {
            return p.replace(new RegExp(o, "g"), n);
        }, __getImgSrc: function (html) {
            var imgReg = /|\/>)/gi, srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i, arr = html.match(imgReg), srcs = [];
            if (arr) {
                for (var i = 0; i < arr.length; i++) {
                    var src = arr[i].match(srcReg), src = src[1];
                    src && srcs.push(src)
                }
                return srcs;
            } else {
                return null;
            }
        }, __addSlash: function (a) {
            return (a.indexOf("/") == 0 ? "" : "/") + a;
        }, replace: function (path, oldUrlOrArr, newUrl) {
            oldUrlOrArr instanceof Array || (oldUrlOrArr = [oldUrlOrArr]);
            var arr = oldUrlOrArr;
            for (var i in arr) var a = arr[i], path = this.__r(path, a, newUrl);
            return path;
        }, img: function (imgUrl, oldUrl, newUrl, http) {
            if (!imgUrl) return;
            http || (http = 'http://'), imgUrl.indexOf(http) == -1 && (imgUrl = http + newUrl + this.__addSlash(imgUrl));
            return pathRepair.replace(imgUrl, oldUrl, newUrl);
        }, detail: function (html, oldUrlOrArr, newUrl, http) {
            if (!html) return;
            http || (http = 'http://');
            var arr = this.__getImgSrc(html), r = [];
            if (arr) {
                for (var i = 0, len = arr.length; i < len; i++) {
                    var a = arr[i];
                    a.indexOf(http) == -1 && (a = http + newUrl + this.__addSlash(a));
                    var b = this.replace(a, oldUrlOrArr, newUrl);
                    r[i] = b;
                }
                for (i = 0; i < len; i++) {
                    var a = arr[i], b = r[i], html = this.__r(html, a, b);
                }
            }
            return html;
        }
    };
    /*测试用例*/
    console.log(pathRepair.detail(html, "121.40.143.145", "www.shuzhiqiang.com", "http://"));
    

    /**选项卡切换效果神器1.0*/ var chooseBar = {
        _ac: "active", _bar: null, _con: null, _fun: null, __reset: function () {
            this._bar.forEach(function (e) {
                e.className = e.className.replace(new RegExp(chooseBar._ac, "g"), "").replace(/  /g, "");
                e.style.cursor = "pointer";
            });
            this._con && (this._con.forEach(function (e) {
                e.style.display = "none";
            }));
        }, __active: function (i) {
            i || (i = 0), this.__reset();
            var b = this._bar[i];
            b.className += " " + this._ac, b.style.cursor = "default";
            this._con && (this._con[i].style.display = "block");
            this._fun && this._fun(i);
        }, click: function (obj) {
            this.init(obj, 'click');
        }, over: function (obj) {
            this.init(obj, 'over');
        }, init: function (obj, type) {
            /**obj的格式说明: { bar:[(必填)按钮的id or class(数组)], con:[(必填)显示内容的id or class(数组)], } 特别说明:在选项卡上面加入.active{ 高亮显示样式 }; */ this._bar = obj.bar;
            if (typeof obj.con == "function") {
                this._fun = obj.con;
            } else {
                this._con = obj.con;
            }
            this.__active();
            var event = 'onclick';
            switch (type) {
                case 'click':
                    event = 'onclick';
                    break;
                case 'over':
                    event = 'onmouseover';
                    break;
            }
            for (var i = 0, len = this._bar.length; i < len; i++) {
                var a = this._bar[i];
                a.index = i;
                a[event] = function () {
                    chooseBar.__active(this.index);
                }
            }
        }
    };
    /*测试用例*//*点击后显示隐藏对应div*//* chooseBar.click({bar: document.querySelectorAll("#bar li"), con: document.querySelectorAll("#con li")}); 点击触发事件*/
    chooseBar.click({
        bar: document.querySelectorAll(".menu li"), con: function (i) {
            alert(i)
        }
    });
var ID = {
        __valid: function (id) {
            return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(id);
        }, getBirthDate: function (cardId) {
            if (!this.__valid(cardId)) return console.log("身份证不合法");
            return cardId.substr(6, 4) + "-" + this.getBirthday(cardId);
        }, getBirthday: function (cardId) {
            if (!this.__valid(cardId)) return console.log("身份证不合法");
            return cardId.substr(10, 2) + "-" + cardId.substr(12, 2);
        }, getSex: function (cardId) {
            if (!this.__valid(cardId)) return console.log("身份证不合法");
            return parseInt(cardId.substr(16, 1)) % 2 == 1 ? "男" : "女";
        }, getAge: function (cardId) {
            if (!this.__valid(cardId)) return console.log("身份证不合法");
            var age = new Date().getFullYear() - cardId.substr(6, 4);
            new Date(new Date().getFullYear() + "-" + this.getBirthday(cardId)) > new Date() && age--;
            return age;
        }
    };
    /**复杂url?data=参数自动获取以及设置*/ var ud = {
        get: function (data) {
            return JSON.parse(hash.getQueryString(data || "data"));
        }, set: function (data, keyName) {
            return "?" + (keyName || "data") + "=" + encodeURIComponent(JSON.stringify(data));
        },
    };

    /**该网页所在的域名目录必须是: 1、设置网页授权域名,否则无法获取openid(微信公众平台后台“右上角头像→功能设置”的配置选项中,修改授权回调域名。请注意,这里填写的是域名(是一个字符串),而不是URL) 2、设置JSAPI支付授权目录,否则无法唤起微信支付窗口(微信支付商户平台“产品中心→开发配置→支付配置→JSAPI支付授权目录”添加具体指向该页面所在域名目录)*/ var getOpenIdUrl = "http://192.168.1.108:9999/wechat/getAccessTokenAndOpenId";
    /*获取openid*/
    var createOrderUrl = "http://192.168.1.108:9999/wepay/createOrder";
    /*创建微信预支付订单*/
    var notifyUrl = "http://www.sg.com:9999/wepay/notifyUrl";
    /*通知url必须为直接可访问的url,不能携带参数。示例:notify_url(https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_7&index=8)*/
    /**微信支付JSAPI唤起支付窗口*/ var wePay = {
        _api: createOrderUrl, _data: {}, __onBridgeReady: function () {
            var d = this._data;
            WeixinJSBridge.invoke('getBrandWCPayRequest', {appId: d.appId, timeStamp: d.timeStamp, nonceStr: d.nonceStr, package: d.package, signType: d.signType, paySign: d.paySign}, function (d) {
                alert("微信返回信息:" + JSON.stringify(d, null, 4));
                if (d.err_msg == "get_brand_wcpay_request:ok") {
                    alert("支付成功!");
                    /*显示支付成功结果页*/
                    location.replace("paySuccessResult.html?body=&price=&out_trade_no=" + d.out_trade_no + "&timeStamp=" + d.timeStamp);
                } else if (d.err_msg == "get_brand_wcpay_request:cancel") {
                    alert("支付取消!");
                    history.go(-1);
                } else if (d.err_msg == "get_brand_wcpay_request:fail") {
                    alert("支付失败!");
                    history.go(-1);
                }
            });
        }, __showWePayDialog: function (data) {
            this._data = data.data;
            if (typeof WeixinJSBridge == "undefined") {
                if (document.addEventListener) {
                    document.addEventListener('WeixinJSBridgeReady', this.__onBridgeReady, false);
                } else if (document.attachEvent) {
                    document.attachEvent('WeixinJSBridgeReady', this.__onBridgeReady);
                    document.attachEvent('onWeixinJSBridgeReady', this.__onBridgeReady);
                }
            } else {
                this.__onBridgeReady();
            }
        }, pay: function (obj) {
            /**舒工自定义调用Ajax 2.0.2*/ $g.ajax({
                post: {url: this._api, data: {body: obj.body, out_trade_no: obj.out_trade_no, total_fee: obj.total_fee, notify_url: obj.notify_url, openid: obj.openid}, noToken: true}, get: {
                    success: function (d) {
                        if (d.code == 200) {
                            wePay.__showWePayDialog(d);
                        } else {
                            alert(JSON.stringify(d, null, 4));
                        }
                    }, error: function (d) {
                        console.log("【报错】" + JSON.stringify(d, null, 4));
                    },
                }
            });
        }
    };
    /*获取code-------------------------------------------------------------------------*/
    var code = hash.getQueryString("code"), openId;
    alert("CODE:" + code);
    /*获取openid-------------------------------------------------------------------------*/
    /**舒工自定义调用Ajax 2.0.2*/ $g.ajax({
        post: {url: getOpenIdUrl, data: {code: code}, noToken: true}, get: {
            success: function (d) {/* alert(JSON.stringify(d, null, 4));*/
                openId = d.data.openid;
                alert("openId:" + openId);
            }, error: function (d) {
                alert(JSON.stringify(d, null, 4));
            },
        }
    });
    /*唤起支付-------------------------------------------------------------------------*/
    var obj = {body: "产品名称", out_trade_no: "SG_order_" + Number(new Date()), total_fee: 1, notify_url: notifyUrl, /* openid: "o07LNv8MhotwnZoWmDfx0oK5ZYik"*/};
    document.querySelector("button").onclick = function () {
        obj.openid = openId;
        wePay.pay(obj);
    }
    /*-------------------------------------------------------------------------*/
var userAgent = {
        _ua: navigator.userAgent, _ual: navigator.userAgent.toLocaleLowerCase(), /**判断是否为PC电脑端浏览器*/ isPC: function () {
            var ua = this._ual;
            return ua.indexOf("pad") == -1 && ua.indexOf("mobile") == -1;
        }, /**判断是否为手机端*/ isPhone: function () {
            var ua = this._ual;
            return ua.indexOf("pad") == -1 && ua.indexOf("mobile") > -1;
        }, /**判断是否为平板电脑*/ isPad: function () {
            var ua = this._ua, isAndroid = /(?:Android)/.test(ua), isFireFox = /(?:Firefox)/.test(ua);
            return /(?:iPad|PlayBook)/.test(ua) || (isAndroid && !/(?:Mobile)/.test(ua)) || (isFireFox && /(?:Tablet)/.test(ua));
        }, /**判断是否是微信浏览器*/ isWeixinBrowser: function () {
            return this._ual.indexOf("micromessenger") != -1;
        }, /**监听是否为苹果电脑自带浏览器safari*/ safariBrowser: function (func) {
            func || (func = function () {
                alert("请不要使用safari这种低端浏览器,我唾弃你的品位!点击关闭,让我们一起安装高大上的谷歌浏览器吧,祝你早日富可敌国!么么哒~");
                window.opener = null;
                /*为了不出现提示框*/
                window.close();
                /*关闭窗口*/
                window.open("http://shuzhiqiang.com/files/googlechrome.dmg");
            });
            var isSafari = /Safari/.test(this._ua) && !/Chrome/.test(this._ua);
            if (isSafari) func();
        }, /**移动端浏览器跳转*/ mobileBrowserRedirect: function (mobilePageOrFunc, webPageOrFunc) {
            var ua = this._ual, ipad = ua.indexOf("ipad") > -1, iphone = ua.indexOf("iphone os") > -1, midp = ua.indexOf("midp") > -1, uc7 = ua.indexOf("rv:1.2.3.4") > -1, uc = ua.indexOf("ucweb") > -1, andriod = ua.indexOf("android") > -1,
                ce = ua.indexOf("windows ce") > -1, wm = ua.indexOf("windows mobile") > -1, wx = ua.indexOf("micromessenger") > -1, isMobile = ipad || iphone || midp || uc7 || uc || andriod || ce || wm || wx;
            if (isMobile) {
                document.querySelector("html").style.display = "none";
                typeof mobilePageOrFunc == "string" && location.replace(mobilePageOrFunc);
                typeof mobilePageOrFunc == "function" && mobilePageOrFunc();
            } else {
                typeof webPageOrFunc == "string" && location.replace(webPageOrFunc);
                typeof webPageOrFunc == "function" && webPageOrFunc();
            }
            return isMobile;
            /*测试用例*/
            /*mobileBrowserRedirect(function () {alert("该页面暂不支持移动端访问,请用电脑访问")})*/
        }, /**判断是移动端浏览器*/ isMobilePhoneBrowser: function (mobilePhoneCallback, padCallback, otherMobileCallback) {
            var ua = this._ua;
            if (/AppleWebKit.*mobile/i.test(ua) || (/MIDP|SymbianOS|NOKIA|SAMSUNG|LG|NEC|TCL|Alcatel|BIRD|DBTEL|Dopod|PHILIPS|HAIER|LENOVO|MOT-|Nokia|SonyEricsson|SIE-|Amoi|ZTE/.test(ua))) {
                if (location.href.indexOf("?mobile") < 0) {
                    try {
                        if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(ua)) {
                            mobilePhoneCallback ? mobilePhoneCallback() : location.replace("手机页面.html");
                            return true;
                        } else if (/iPad/i.test(ua)) {
                            padCallback ? padCallback() : location.replace("平板页面.html");
                            return true;
                        } else {
                            otherMobileCallback ? otherMobileCallback() : location.replace("其他移动端页面.html");
                            return true;
                        }
                    } catch (e) {
                        console.log(e);
                    }
                }
            }
            return false;
        }, /**判断是IOS系统*/ isIOS: function () {
            var u = this._ua, app = navigator.appVersion;
            var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
            /*ios终端*/
            return isIOS;
        }, /**判断是Android系统*/ isAndroid: function () {
            var u = this._ua, app = navigator.appVersion;
            var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;
            /*g*/
            return isAndroid
        },
    }
var swiper = {
        _swiper: null, _swiperScroll: null, __scrollTop: function () {
            top.scrollTo(0, 0);
            window.scrollTo(0, 0);
        }, init: function (type, sel) {
            this.__scrollTop();
            type || (type = 0);
            var effect = "slide";
            /*默认为"slide"(位移切换),可设置为'slide'(普通切换、默认),"fade"(淡入)"cube"(方块)"coverflow"(3d流)"flip"(3d翻转)。*/
            switch (type) {
                case 0:
                    effect = "slide";
                    break;
                case 1:
                    effect = "fade";
                    break;
                case 2:
                    effect = "cube";
                    break;
                case 3:
                    effect = "coverflow";
                    break;
                case 4:
                    effect = "flip";
                    break;
                case 5:
                    break;
                default:
                    effect = "slide";
            }
            this._swiper = new Swiper(sel || '.swiper-container', {
                autoplay: true,
                speed: 500,
                effect: effect,
                loop: true,
                grabCursor: true,
                cubeEffect: {shadow: false, slideShadows: false, /*去掉coverflow下的背景阴影*/},
                coverflowEffect: {rotate: 50, stretch: 300, depth: 300, modifier: 1, slideShadows: false, /*去掉coverflow下的背景阴影*/},
                flipEffect: {slideShadows: false, /*去掉coverflow下的背景阴影*/},
                pagination: {el: '.swiper-pagination',},
                navigation: {nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev',},
            });
        }, initScroll: function (sel) {
            this.__scrollTop();
            this._swiperScroll = new Swiper(sel || '.swiper-scroll-container', {direction: 'vertical', slidesPerView: 'auto', freeMode: true, mousewheel: true, scrollbar: {el: '.swiper-scrollbar', hide: true, /*停止滚动后,滚动条默默地消失…*/},});
        },
    };
/**倒计时*/
    var countDown = {
        fromTotalTime: function (fromTime, intervalCallback, nearEndCallback, endCallback) {
            var m, s;
            if (fromTime >= 0) {
                m = Math.floor(fromTime / 60), s = Math.floor(fromTime % 60), intervalCallback && intervalCallback({minutes: m, seconds: s}), nearEndCallback && (fromTime == 60) && nearEndCallback("还剩1分钟");
                setTimeout(function () {
                    countDown.fromTotalTime(--fromTime, intervalCallback, nearEndCallback, endCallback)
                }, 1000);
            } else {
                endCallback && endCallback("时间到");
            }
        }, toDateTime: function (datetime, intervalCallback, nearEndCallback, endCallback) {
            var difTime = new Date(datetime).getTime() - new Date().getTime();
            var res, y, d, h, m, s, os = 1000;
            if (difTime >= 0) {
                y = Math.floor(difTime / os / 60 / 60 / 24 / 365), d = Math.floor(difTime / os / 60 / 60 / 24 % 365), h = Math.floor(difTime / os / 60 / 60 % 24), m = Math.floor(difTime / os / 60 % 60), s = Math.floor(difTime / os % 60), res = {
                    year: y,
                    day: d,
                    hour: h,
                    minutes: m,
                    seconds: s
                }, nearEndCallback && (difTime == 60) && nearEndCallback("还剩1分钟");
            } else {
                endCallback && endCallback("时间到");
            }
            intervalCallback && intervalCallback(res);
            setTimeout(function () {
                countDown.toDateTime(datetime, intervalCallback, nearEndCallback, endCallback);
            }, os);
        }
    };
    /*测试用例*/
    countDown.fromTotalTime(1 * 60, function (res) {
        document.querySelector("body").innerText = res.minutes + "分" + res.seconds + "秒";
    }, function (e) {
        alert(e);
        /*还剩1分钟!*/
    }, function (e) {
        alert(e);
        /*时间到!*/
    })
    countDown.toDateTime("2019-10-24 00:00:00", function (res) {
        document.querySelector("body").innerText = res.year + "年" + res.day + "天" + res.hour + "时" + res.minutes + "分" + res.seconds + "秒";
    })
//模拟双击事件----------------------------------------------------------------
    function doubleClick(sel, func) {
        var timeStamp = null;
        document.querySelector(sel).onclick = function (e) {
            if (timeStamp && e.timeStamp - timeStamp < 300) {/*间隔低于300毫秒连续单击认为是双击*/
                func && func();
            } else {
                timeStamp = e.timeStamp
            }
        };
    }

    /*测试用例*/
    doubleClick("button", function () {
        alert("你刚刚双击了按钮");
    })

//原生的双击----------------------------------------------------------------
dom.ondblclick=function(){
    //双击事件   
}
    var select = {
        /**获取下拉框的value和text*/ get: function (sel) {
            typeof sel == "string" && (sel = document.querySelector(sel));
            sel = sel.options[sel.selectedIndex];
            return {value: sel.value, text: sel.text};
        }, /**下拉框html初始化*/ init: function (sel, dataArray, index) {
            typeof sel == "string" && (sel = document.querySelector(sel));
            var html = "";
            for (var i in dataArray) {
                var data = dataArray[i];
                html += "";
            }
            sel.innerHTML = html;
            return html;
        }
    };
/**淡入淡出,需要引入jquery*/
    function setTimeFadeInOut(sel, time, speed) {
        typeof sel == "string" && (sel = document.querySelector(sel));
        sel = $(sel);
        time || (time = 3);
        speed || (speed = "fast");
        sel.stop().fadeIn(speed);
        setTimeout(function () {
            sel.stop().fadeOut(speed);
        }, time * 1000);
    }

    /*测试用例*/
    setTimeFadeInOut("sel", 3, "fast");
/**间隔屏蔽功能*/
    function setTimePointerEvents(sel, time) {
        sel = typeof sel == "string" ? document.querySelector(sel) : (sel instanceof jQuery ? sel[0] : sel);
        time || (time = 1);
        sel.style.pointerEvents = "none";
        setTimeout(function () {
            sel.style.pointerEvents = "auto";
        }, time * 1000)
    }

    /*测试用例*/
    setTimePointerEvents("sel", 3);
var img = {
        getSize: function (imgUrl, callback) {
            /**设置div为图片实时预加载宽度、高度*/ imgUrl = imgUrl + "?" + Number(new Date());
            var img = new Image();
            img.src = imgUrl;
            /* 定时执行获取宽高*/
            var set = setInterval(function () {
                var obj = {width: img.width, height: img.height};
                if (obj.width > 0 && obj.height > 0) {
                    clearInterval(set);
                    callback && callback(obj);
                }
            }, 1);
        }, setRealSize: function (sel, attr, imgUrl) {
            var DIV = document.querySelector(sel)
            /**设置div为图片真实宽度、高度*/ imgUrl = imgUrl + "?" + Number(new Date());
            var img = new Image();
            img.src = imgUrl;
            img.onload = function () {
                (attr == "width" || attr == "size") && (DIV.style.width = this.width + "px");
                (attr == "height" || attr == "size") && (DIV.style.height = this.height + "px");
            };
        }, setRealtimeSize: function (sel, attr, imgUrl) {
            var DIV = document.querySelector(sel)
            /**设置div为图片实时预加载宽度、高度*/ imgUrl = imgUrl + "?" + Number(new Date());
            var img = new Image();
            img.src = imgUrl;
            /* 定时执行获取宽高*/
            var set = setInterval(function () {
                var iw = img.width;
                var ih = img.height;
                if (iw > 0 && ih > 0) {
                    clearInterval(set);
                    (attr == "width" || attr == "size") && (DIV.style.width = iw + "px");
                    (attr == "height" || attr == "size") && (DIV.style.height = ih + "px");
                }
            }, 1);
        }
    };
    /*测试用例*/
    img.setRealSize("div", "size", "https://img.zcool.cn/community/019a455b3e9007a80120b959405c57.jpg");
    img.setRealtimeSize("div", "size", "https://img.zcool.cn/community/019a455b3e9007a80120b959405c57.jpg");
    img.getSize("https://www.baidu.com/img/bd_logo1.png", function (obj) {
        console.log(obj);
        /*获取百度图片的宽度高度*/
    })
    var replace = {
        /**替换字符串里面所有指定字符*/ replaceWords: function (str, replacedWord, replaceWord) {
            replacedWord || (replacedWord = " ");
            replaceWord || (replaceWord = "");
            return str.replace(new RegExp(replacedWord, "g"), replaceWord);
        }, /**去掉最后一个字符串*/ removeLastChar: function (s) {
            s = s.toString();
            return s.substr(0, s.length - 1);
        }, /**去掉字符串中的特殊字符*/ removeSpecialCharacter: function (s) {/* 去掉转义字符*/
            s = s.replace(/[\'\"\\\/\b\f\n\r\t]/g, '');
            /* 去掉特殊字符*/
            s = s.replace(/[\@\#\$\%\^\&\*\(\)\{\}\:\"\L\<\>\?\[\]]/g, '');
            return s;
        }
    };
    /*测试用例*/
    alert(replace.replaceWords("有天我睡醒看到我的身边没有你", "我", "你"))

    var ip = {
        isLocal: function () {
            var lh = top.location.href;
            return (lh.indexOf("localhost") > -1 || lh.indexOf("127.0.0.1") > -1);
        }, localIP: function (callback) {
            var ip = {}, R = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection, M = {optional: [{RtpDataChannels: true}]}, S = {iceServers: [{urls: "stun:stun.services.mozilla.com"}]}, f = function () {
            };
            if (!R) {
                var win = iframe.contentWindow, R = win.RTCPeerConnection || win.mozRTCPeerConnection || win.webkitRTCPeerConnection;
            }
            var P = new R(S, M);

            function h(c) {
                var r = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/;
                var a = r.exec(c)[1];
                if (ip[a] === undefined) {
                    callback(a);
                }
                ip[a] = true;
            }

            P.onicecandidate = function (i) {
                if (i.candidate) h(i.candidate.candidate);
            };
            P.createDataChannel("");
            P.createOffer(function (r) {
                P.setLocalDescription(r, f, f);
            }, f);
            setTimeout(function () {
                var ls = P.localDescription.sdp.split('\n');
                ls.forEach(function (l) {
                    if (l.indexOf('a=candidate:') === 0) h(l);
                });
            }, 1);
        }
    };
    /*测试用例*/
    ip.localIP(function (ip) {
        alert('您本机的局域网(内网)IP是 ' + ip);
    });
    /**设置快捷键*/onkeyup = function (e) {
        var k = e.keyCode || e.which || e.charCode, ck = e.ctrlKey || e.metaKey, ak = e.altKey, sk = e.shiftKey;
        /**独立键*/
        if (k == 13) {/*按下回车键Enter↩的时候执行*/
        }
        if (k == 27) {/*按下退出键Esc的时候执行*/
        }
        if (k == 36) {/*执行Home*/
        }
        if (k == 35) {/*执行End*/
        }
        if (k == 48 || k == 96) {/*执行0、Num0*/
        }
        if (k == 49 || k == 97) {/*执行1、Num1*/
        }
        if (k == 37 || k == 38 || k == 27 || k == 8) { /*按下 ← ↑ Esc 
var cookie = {
        getAll: function() {
            var arr = unescape(document.cookie).split("; "),
                o = {};
            for (var i = 0, len = arr.length; i < len; i++) {
                var a = arr[i],
                    index = a.indexOf("="),
                    b = a.substr(0, index),
                    c = a.substr(index + 1);
                o[b] = c
            }
            return o;
        },
        save: function(obj, day, path) {
            for (var a in obj) {
                var b = obj[a];
                this.set(a, b, day, path);
            }
        },
        dels: function(arr, path) {
            for (var i in arr) {
                var a = arr[i];
                this.del(a, path);
            }
        },
        set: function(key, val, day, path) {
            if (val == null || val == undefined) return;
            var k = key,
                d = day,
                d = d || 1,
                e = new Date();
            e.setDate(e.getDate() + d);
            val instanceof Array && (val = val.join("||")), val instanceof Object && (val = JSON.stringify(val));
            document.cookie = k + "=" + escape(val.toString()) + ((d == null) ? "" : ";expires=" + e.toGMTString()) + "; path=/" + (path || "");
        },
        get: function(key) {
            var k = key;
            if (document.cookie.length > 0) {
                var s = document.cookie.indexOf(k + "=");
                if (s != -1) {
                    s = s + k.length + 1;
                    var e = document.cookie.indexOf(";", s);
                    if (e == -1) e = document.cookie.length;
                    return unescape(document.cookie.substring(s, e));
                }
            }
            return "";
        },
        getJOSN: function(key) {
            return JSON.parse(this.get(key) || '{}');
        },
        getArray: function(key) {
            return this.get(key).split("||");
        },
        del: function(key, path) {
            var k = key,
                e = new Date(),
                val = this.get(k);
            e.setTime(e.getTime() - 1);
            if (val != null) document.cookie = k + "=" + val + ";expires=" + e.toGMTString() + "; path=/" + (path || "");
        },
        clearAll: function(path) {
            var k = document.cookie.match(/[^ =;]+(?=\=)/g);
            if (k) {
                for (var i = k.length; i--;) document.cookie = k[i] + '=0;expires=' + new Date(0).toUTCString() + "; path=/" + (path || "");
            }
        },
        setToken: function(val, day, path) {
            this.set("token", val, day, path)
        },
        getToken: function(path) {
            return this.get("token", path)
        },
        setTempToken: function(val, day, path) {
            this.set("tempToken", val, day, path)
        },
        getTempToken: function(path) {
            return this.get("tempToken", path)
        }
    }
    /*测试用例*/
    cookie.save({username: "admin", password: "123456"}, 365);
    /*批量存储*/
    cookie.dels(["username", "password"]);
    /*批量删除*/
    console.log(cookie.getAll());//获取所有缓存数据转换为对象
    /*屏蔽拷贝图片________________________________________________*/
    function DontCopyMyImage() { /*知识产权保护措施:禁止右键查看、禁止复制文本、禁止使用快捷键截图(很遗憾无法禁用Print Screen屏幕截图按钮)*/
        var HTMLDOM = document.querySelector("html");
        /*屏蔽拖拽保存图片*/
        window.ondragstart = window.ontouchmove = document.ondragstart = document.ontouchmove = function (e) {
            e.preventDefault();
            return false;
        };
        /*防止用键盘截屏快捷键截图*/
        var hideBodyIntervalID1, hideBodyIntervalID2;
        /*老子设置两个毫秒级的刷新事件干死你了!*/
        window.oncontextmenu = document.oncontextmenu = new Function("event.returnValue=false;");
        window.onselectstart = document.onselectstart = new Function("event.returnValue=false;");
        window.oncopy = document.oncopy = new Function("event.returnValue=false;");
        window.onkeydown = document.onkeydown = function (e) {
            var currKey = e.keyCode || e.which || e.charCode;
            var isKeyF1toF12 = currKey > 111 && currKey < 124 && currKey != 116;
            var isPrintOrInsert = currKey == 42 || currKey == 44 || currKey == 45 || currKey == 145;
            var isCombinatorialKey = event.shiftKey || event.ctrlKey || event.altKey || e.shiftKey || e.ctrlKey || e.altKey;
            if (isKeyF1toF12 || isCombinatorialKey || isPrintOrInsert) {
                hideBody();
                CloseWebPage();
                /* window.open("javascript: alert('朋友!您是想要截屏还是查看源代码呢?\\r\\n如果没办法拷贝截图和代码可以\\r\\n联系舒工");*/
            }
        };
        window.onblur = document.onblur = hideBody;
        window.onfocus = document.onfocus = showBody;

        function hideBody() {
            hideBodyIntervalFunc();
            hideBodyIntervalFunc();
            hideBodyIntervalID1 = setInterval(hideBodyIntervalFunc, 1);
            hideBodyIntervalID2 = setInterval(hideBodyIntervalFunc, 1);
        }

        function hideBodyIntervalFunc() {
            HTMLDOM.style.opacity = "0";
            HTMLDOM.style.display = "none";
            HTMLDOM.style.visibility = "hidden";
            HTMLDOM.style.opacity = "0";
            HTMLDOM.style.display = "none";
            HTMLDOM.style.visibility = "hidden";
            HTMLDOM.style.opacity = "0";
            HTMLDOM.style.display = "none";
            HTMLDOM.style.visibility = "hidden";
            HTMLDOM.style.opacity = "0";
            HTMLDOM.style.display = "none";
            HTMLDOM.style.visibility = "hidden";
            HTMLDOM.style.opacity = "0";
            HTMLDOM.style.display = "none";
            HTMLDOM.style.visibility = "hidden";
            HTMLDOM.style.opacity = "0";
            HTMLDOM.style.display = "none";
            HTMLDOM.style.visibility = "hidden";
            HTMLDOM.style.opacity = "0";
            HTMLDOM.style.display = "none";
            HTMLDOM.style.visibility = "hidden";
            HTMLDOM.style.opacity = "0";
            HTMLDOM.style.display = "none";
            HTMLDOM.style.visibility = "hidden";
            HTMLDOM.style.opacity = "0";
            HTMLDOM.style.display = "none";
            HTMLDOM.style.visibility = "hidden";
            HTMLDOM.style.opacity = "0";
            HTMLDOM.style.display = "none";
            HTMLDOM.style.visibility = "hidden";
            HTMLDOM.style.opacity = "0";
            HTMLDOM.style.display = "none";
            HTMLDOM.style.visibility = "hidden";
            HTMLDOM.style.opacity = "0";
        }

        function showBody() {
            clearInterval(hideBodyIntervalID1);
            clearInterval(hideBodyIntervalID2);
            HTMLDOM.style.display = "block";
            HTMLDOM.style.visibility = "visible";
            HTMLDOM.style.opacity = "1";
        }

        /*强制关闭不提示*/
        function CloseWebPage() {
            if (navigator.userAgent.indexOf("MSIE") > 0) {
                if (navigator.userAgent.indexOf("MSIE 6.0") > 0) {
                    window.opener = null;
                    window.close();
                } else {
                    window.open('', '_top');
                    top.close();
                }
            } else if (navigator.userAgent.indexOf("Firefox") > 0) {
                window.top.location.replace("about:blank")
            } else {
                window.opener = null;
                window.open('', '_self', '');
                window.close();
            }
        }
    }

    /*________________________END________________________ 屏蔽拷贝图片________________________*/

/**将form表单各个参数组合为字符串形式*/
/**获取指定form中的所有的对象*/
function getElements(formId) {
        var form = document.getElementById(formId);
        var elements = [];
        var tagElements = form.getElementsByTagName('input');
        for (var j = 0; j < tagElements.length; j++) {
            elements.push(tagElements[j]);
        }
        var tagElements = form.getElementsByTagName('select');
        for (var j = 0; j < tagElements.length; j++) {
            elements.push(tagElements[j]);
        }
        var tagElements = form.getElementsByTagName('textarea');
        for (var j = 0; j < tagElements.length; j++) {
            elements.push(tagElements[j]);
        }
        return elements;
    }
/**组合URL*/function serializeElement(element) {
        var method = element.tagName.toLocaleLowerCase();
        var parameter;
        if (method == 'select') {
            parameter = [element.name, element.value];
        }
        switch (element.type.toLocaleLowerCase()) {
            case 'submit':
            case 'hidden':
            case 'password':
            case 'text':
            case 'date':
            case 'textarea':
                parameter = [element.name, element.value];
                break;
            case 'checkbox':
            case 'radio':
                if (element.checked) {
                    parameter = [element.name, element.value];
                }
                break;
        }
        if (parameter) {
            var key = encodeURIComponent(parameter[0]);
            if (key.length == 0) return;
            if (parameter[1].constructor != Array) parameter[1] = [parameter[1]];
            var values = parameter[1];
            var results = [];
            for (var i = 0; i < values.length; i++) {
                results.push(key + '=' + encodeURIComponent(values[i]));
            }
            return results.join('&');
        }
    }
/**调用方法*/
function formToConnectionParameters(formId) {
        var elements = getElements(formId);
        var queryComponents = [];
        for (var i = 0; i < elements.length; i++) {
            var queryComponent = serializeElement(elements[i]);
            if (queryComponent) {
                queryComponents.push(queryComponent);
            }
        }
        return queryComponents.join('&');
    }
/**form表单是否有未填写内容*/
function formHasNull(formId) {
        var form = document.getElementById(formId);
        for (var i = 0; i < form.elements.length; i++) {
            var feled = form.elements[i];
            switch (feled.type) {
                case undefined:
                case 'button':
                case 'file':
                case 'reset':
                case 'submit':
                    break;
                case 'checkbox':
                case 'radio':
                    if (!feled.checked) {
                        return true;
                        break;
                    }
                default:
                    if (feled.value.replace(/\ |\ /g, "") == "") {
                        return true;
                        break;
                    }
            }
        }
        return false;
    }
$g.$utils.hash = {
    get(win) {
        return decodeURIComponent((win || top).location.hash.substr(1));
    }, getSearchAndHash(win) {
        win || (win = top);
        return decodeURIComponent(win.location.search + win.location.hash);
    }, set(hash, win, isReload) {
        hash || (hash = "");
        win = win || top;
        win.location.hash = hash;
        isReload && win.location.reload();
    }, addListener(win) {
        (win || window).onhashchange = function () {
            this.location.reload();
        }
    }, getQueryString(name, win, isEncode) {
        var r = (win || top).location.search.substr(1).match(new RegExp("(^|&)" + name + "=([^&]*)(&|$)"));
        if (r != null) {
            return isEncode ? r[2] : decodeURIComponent(r[2]);
        }
        return null;
    }, parseQuery(url) {
        var reg = /([^=&\s]+)[=\s]*([^&\s]*)/g, ls = url || location.search.substr(1), obj = {};
        while (reg.exec(ls)) {
            obj[RegExp.$1] = decodeURIComponent(RegExp.$2);
        }
        return obj;
    }, getToken() {
        return this.getQueryString("token")
    }, setUrlSearch(search, win, isReload) { /*此方法可以点击网页返回按钮*/
        win = win || top;
        win.history.pushState(null, null, search || "./");
        isReload && win.location.reload();
    }, replceUrlSearch(search, win, isReload) { /*此方法无网页返回按钮行为*/
        win = win || top;
        win.history.replaceState(null, null, search || "./");
        isReload && win.location.reload();
    }, getFileName() {
        var lp = location.pathname, fn = lp.substr(lp.lastIndexOf("/") + 1);
        return fn.substr(0, fn.lastIndexOf("."));
    }
};







home  about  contacts
$g.$utils.screen = {
    /**实现F11全屏效果*/
    fullScreen() {
        var docElm = document.documentElement;
        /*W3C*/
        if (docElm.requestFullscreen) {
            docElm.requestFullscreen();
        }/*FireFox */ else if (docElm.mozRequestFullScreen) {
            docElm.mozRequestFullScreen();
        }/*Chrome等 */ else if (docElm.webkitRequestFullScreen) {
            docElm.webkitRequestFullScreen();
        }/*IE11*/ else if (docElm.msRequestFullscreen) {
            docElm.msRequestFullscreen();
        }
    },
    /**退出F11全屏*/
    exitFullScreen() {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if (document.webkitCancelFullScreen) {
            document.webkitCancelFullScreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }
    },
    /**判断全屏模式是否是可用*/
    isFullscreenEnabled() {
        return document.fullscreenEnabled || document.mozFullScreenEnabled || document.webkitFullscreenEnabled || document.msFullscreenEnabled || false;
    },
    /**判断整个页面被一个标签铺满*/
    isFullscreenForNoScroll() {
        var explorer = window.navigator.userAgent.toLowerCase();
        if (explorer.indexOf("chrome") > -1) {/*webkit*/
            return (document.body.scrollHeight === window.screen.height && document.body.scrollWidth === window.screen.width);
        } else {/*IE 9+  fireFox*/
            return (window.outerHeight === window.screen.height && window.outerWidth === window.screen.width);
        }
    },
    /**判断是否全屏*/
    isFullScreen() {
        return document.fullscreenElement || document.msFullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement ? true : false;
    },
    /**实现局部div、dom元素全屏*/
    fullScreenForDOM(sel) {
        typeof sel == "string" && (sel = document.querySelector(sel));
        /**el是具体的dom元素*/var rfs = sel.requestFullScreen || sel.webkitRequestFullScreen || sel.mozRequestFullScreen || sel.msRequestFullScreen, wscript;
        if (typeof rfs != "undefined" && rfs) {
            rfs.call(sel);
            return;
        }
        if (typeof window.ActiveXObject != "undefined") {
            wscript = new ActiveXObject("WScript.Shell");
            if (wscript) {
                wscript.SendKeys("{F11}");
            }
        }
    },
    exitFullScreenForDOM(sel) {
        typeof sel == "string" && (sel = document.querySelector(sel));
        /**el是具体的dom元素*/var el = document, cfs = sel.cancelFullScreen || sel.webkitCancelFullScreen || sel.mozCancelFullScreen || sel.exitFullScreen, wscript;
        if (typeof cfs != "undefined" && cfs) {
            cfs.call(el);
            return;
        }
        if (typeof window.ActiveXObject != "undefined") {
            wscript = new ActiveXObject("WScript.Shell");
            if (wscript != null) {
                wscript.SendKeys("{F11}");
            }
        }
    }
};
/**递归循环方法(可设置delay延时递归)*/

function dg(arr, i, delay) {
    i || (i = 0), delay || (delay = 0);
    var a = arr[i];
    //这里写代码
    i++, setTimeout(function () {
        i < arr.length && dg(arr, i, delay);
    }, delay)
}

var arr =
    dg(arr);
//点击全局页面其他部分→隐藏指定DOM
      document.onmousedown = function(e) {
        e.path.indexOf(指定DOM) == -1 && 隐藏方法();
      };
//顶部导航条(菜单)随着滚动条隐藏:1、滚动条往下隐藏导航条;2、滚动条往上显示导航条
    var initScroll = function () {
        var nav = document.querySelector("导航条"), nh = nav.offsetHeight, beforeScrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0, html = document.querySelector("html");
        onscroll = function () {
            var afterScrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0, hy = html.getBoundingClientRect().y;
            if (afterScrollTop > beforeScrollTop && hy < -nh) {
                nav.style.marginTop = -1 * nh + "px";
                hy < -window.innerHeight && 显示返回顶部按钮();
            } else {
                nav.style.marginTop = 0;
                隐藏返回顶部按钮();
            }
            beforeScrollTop = afterScrollTop;
        }
    };
    initScroll();
/*获取子DOM元素在父元素里面的索引位置(是第几个元素)*/
    function getNodeListIndex(childNode) {
        return childNode && childNode.parentNode ? Array.prototype.indexOf.call(childNode.parentNode.children, childNode) : null;
    }


/*去掉html标签(真正意义上去掉所有html标签包括内嵌的css样式)*/
    stripHTML: function(html, isRemoveNewLine) {
        var t = document.createElement("div");
        t.innerHTML = html;
        document.querySelector("html").appendChild(t);
        var r = t.innerText;
        t.parentNode.removeChild(t);
        isRemoveNewLine && (r = r.replace(/[\r\n]/g, ""));
        return r;
    },


/*去掉回车换行*/
.replace(/[\r\n]/g,""));



表头1 表头2
内容1 内容2
内容1 内容2
内容1 内容2
内容1 内容2
内容1 内容2
/*任意字符串转为像素单位*/
    var getPx = function (num) {
        num || (num = 0), num = num.toString().toLowerCase();
        return num + ((num.indexOf('px') > -1 || num.indexOf('%') > -1) ? '' : 'px');
    }
    /*获取鼠标移动方向*/
    function getMouseDirection(sel) {
        var wrap = document.querySelector(sel);
        var hoverDir = function (e) {
            var w = wrap.offsetWidth, h = wrap.offsetHeight, x = (e.clientX - wrap.offsetLeft - (w / 2)) * (w > h ? (h / w) : 1), y = (e.clientY - wrap.offsetTop - (h / 2)) * (h > w ? (w / h) : 1),
                direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4;
            /* 上(0) 右(1) 下(2) 左(3)*/
            console.log(direction);
        }
        if (window.addEventListener) {
            wrap.addEventListener('mousemove', hoverDir, false);
        } else if (window.attachEvent) {
            wrap.attachEvent('mousemove', hoverDir);
        }
    }
    getMouseDirection('body');
    /*DOM类型判断*/
    var isDOM = (typeof HTMLElement === 'object') ? function (obj) {
        return obj instanceof HTMLElement;
    } : function (obj) {
        return obj && typeof obj === 'object' && obj.nodeType === 1 && typeof obj.nodeName === 'string';
    }
    /*获取DOM*/
    var __getDOM = function (dom) {
        return (typeof dom == 'string' ? document.querySelector(dom) : dom) || null;
    }
    //自由化传参【可以传入数组、离散的独立参数】
    var __getFreeParams = function (args) {
        var ra = [], arr = Array.isArray(args) ? args : arguments;
        for (var i = 0, len = arr.length; i < len; i++) {
            var a = arr[i];
            a != undefined && ra.push(a);
        }
        return ra;
    }
    console.log(__getFreeParams(1, 2, 3, 4));
    /*监听DIV内容发生变化*/
    function addChangeListener(sel, changeEvent) {
        document.querySelector(sel).addEventListener('DOMNodeInserted', function () {
            changeEvent(this.innerHTML);
        });
    };
    //在DOM开头加渲染
    function insertBefore(sel, html) {
        document.querySelector(sel).insertAdjacentHTML("afterbegin", html);
    }

    /*js实现jquery的append方法*/
    //在DOM结尾追加渲染
    function append(sel, html) {
        document.querySelector(sel).insertAdjacentHTML("beforeend", html);
    }
dom.scrollIntoView({behavior: "smooth", block: "nearest", inline: "nearest"});//缓慢滚动
    /**
     【behavior 可选】
     定义动画过渡效果, "auto", "instant", 或 "smooth" 之一。默认为 "auto"。
     【block 可选】
     定义垂直方向的对齐, "start", "center", "end", 或 "nearest"之一。默认为 "start"。
     【inline 可选】
     定义水平方向的对齐, "start", "center", "end", 或 "nearest"之一。默认为 "nearest"。
     */

$('html').stop().animate({scrollTop: 滚动顶部位置}, 'fast', function () {console.log('滚动结束');});
//获取伪元素的样式
    var getPseudoElementStyle = function (sel, pseudo, propertyName) {
        return window.getComputedStyle(document.querySelector(sel), ':' + (pseudo || 'before')).getPropertyValue(propertyName || 'display');
    };
    console.log(getPseudoElementStyle('h1', 'after', 'content'));//测试
/*全站变成灰色(去色)*/
* {
    filter: grayscale(100%);
    -webkit-filter: grayscale(100%);
    -moz-filter: grayscale(100%);
    -ms-filter: grayscale(100%);
    -o-filter: grayscale(100%);
    filter: progid:DXImageTransform.Microsoft.BasicImage(grayscale=1);
    -webkit-filter: grayscale(1);
}
&::after {
    /* 向下的直角三角形箭头 */
    content: "";
    position: absolute;
    top: 0px;
    right: 0px;
    width: 0;
    height: 0;
    border: 5px solid transparent;
    border-top-color: red;
}

&::after {
    /* 向右的直角三角形箭头 */`
    content: "";
    position: absolute;
    top: 0px;
    right: 0px;
    width: 0;
    height: 0;
    border: 5px solid transparent;
    border-left-color: red;
}
//Vue在新窗口弹出单页面
        const { href } = this.$router.resolve({
          path: "/singleNewsDetail",
          query: { item: this.item, id: this.id }
        });
        window.open(href, "_blank");
//Vue节点绑定事件获取当前元素,并修改其样式
 @click="$event.srcElement.style.display='none'"

// 当前点击的元素
$event.target;//等同于$event.srcElement
// 绑定事件的元素
$event.currentTarget;
// (target与currentTarget的区别主要体现在使用事件委托时,发生事件委托时,点击的元素与绑定事件的元素非同一元素,反之不发生事件委托时,两者相同,是同一元素)

// 获得绑定事件元素的前一个节点信息(包含元素节点、属性节点、文本节点、注释节点)
$event.currentTarget.previousSibling;
// 获得绑定事件元素的前一个元素节点(只包含元素节点,只有html内容)
$event.currentTarget.previousElementSibling;
// 下一个元素信息获取使用 nextSibling、nextElementSibling

// 获得绑定事件元素的父节点信息
$event.currentTarget.parentNode;
// 获得绑定事件元素的父级元素
$event.currentTarget.parentElement;

// 获得绑定事件元素的第一个子节点信息
$event.currentTarget.firstChild;
// 获得绑定事件元素的第一个子元素
$event.currentTarget.firstElementChild;

// 获得绑定事件元素中id为ceshi的元素集合
$event.currentTarget.getElementById("ceshi");
// 获得绑定事件元素中class为ceshi的元素集合
$event.currentTarget.getElementsByClassName("ceshi");

// 获得绑定事件元素的的内容(类似jquery的text())
$event.currentTarget.textContent;
// 获得绑定事件元素的的内容(类似jquery的html())
$event.currentTarget.innerHTML;
// 获得绑定事件元素的ceshi属性(类似jquery的attr('ceshi'))
$event.currentTarget.getAttributeNode("ceshi");

// 点击删除当前元素
$event.currentTarget.parentElement.removeChild(event.currentTarget);
// 点击删除当前元素的父级元素
$event.currentTarget.parentElement.parentElement.removeChild(event.currentTarget.parentElement);
/* 用白色渐变遮罩隐藏未显示完的文章部分 */
        &::after {
          content: "";
          position: absolute;
          left: 0;
          bottom: 0;
          width: 100%;
          height: 100px;
          /*从上往下渐变背景*/
          background: -webkit-linear-gradient(
            transparent,
            white
          ); /* Safari 5.1 - 6.0 */
          background: -o-linear-gradient(
            transparent,
            white
          ); /* Opera 11.1 - 12.0 */
          background: -moz-linear-gradient(
            transparent,
            white
          ); /* Firefox 3.6 - 15 */
          background: linear-gradient(
            transparent,
            white
          ); /* 标准的语法(必须放在最后) */
        }

 :style="{backgroundImage:'url('+item.bgUrl+')'}" 



 :style="{marginLeft:-100*currentIndex+'px'}" 


    单行省略号 {
        /*单行省略号*/
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }

    多行省略号 {
        /*多行省略号*/
        overflow: hidden;
        word-break: break-all;/*单词分割换行*/
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 行数(默认3);
        height: 高度px;
    }
    /*js代码添加省略号*/
    function addEllipsis(text, maxLength=10, suffix="…") {
        text=text.toString();
        return text.length > maxLength ? text.substr(0, maxLength - 1) + suffix : text;
    }
    //判断文本内容是否超出了外层DIV的高度、宽度,此时出现了纵向、横向滚动条(如果用了overflow: hidden;则不会出现滚动条)
    if (DOM.scrollHeight > DOM.clientHeight) {
        //设置paddingRight='10px'
        //设置对应的移入Tip完整内容提示框(通常和CSS{display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 3;overflow: hidden;height:}高度px;多行省略号搭配使用)
    }
    if (DOM.scrollWidth > DOM.clientWidth) {
        //设置对应的移入Tip完整内容提示框(通常和CSS{overflow: hidden;white-space: nowrap;text-overflow: ellipsis;}多行省略号搭配使用)
    }
    //递归把不同层级深度的数组元素转换为扁平化同一个层级的数组
    function p(a, b = []) {Array.isArray(a) ? a.forEach(function (c) {p(c, b);}) : b.push(a);return b;}
    console.log(p([1, [2, [3, 4], 5], 6]));
/*屏蔽移动端滑动、PC端滑动鼠标滚轮事件*/
function disableTouchmoveAndMouseWheel(sel, bool) { /*bool:false禁止,true解除禁止*/
    sel = typeof sel == "string" ? document.querySelectorAll(sel) : [sel];
    bool = Boolean(bool);
    var arr = sel;
    for (var i = 0, len = arr.length; i < len; i++) {
        var a = arr[i];
        a.ontouchmove = a.onmousewheel = function (e) {
            bool || e.preventDefault && e.preventDefault();
            e.returnValue = bool;
            bool || e.stopPropagation && e.stopPropagation();
            return bool;
        }
    }
}





/*禁用浏览器返回按钮、禁用浏览器回退按钮*/
function forbiddenBack() {
    history.pushState(null, null, document.URL);//用当前页面网址覆盖最近的历史记录
    window.addEventListener("popstate", function (e) {
        history.pushState(null, null, document.URL);
    }, false);
}

forbiddenBack();
//获取本地国家语言、语种类别
var lang = navigator.userLanguage||navigator.language;//常规浏览器或者IE本地化语言
lang = lang.toLowerCase().substr(0,2);//截取前两位支付
console.log(lang);
/*获取当前页面的最高层级*/
    var getMaxZIndex = () => {
        var arr = [...document.all].map(e => +window.getComputedStyle(e).zIndex || 0);
        return arr.length ? Math.max(...arr) : 0;
    };
/*模糊*/filter: blur(5px);


请在此处输入描述内容…

/*自定义原生添加ClassName,模仿JQuery addClass() 方法*/
var Class = {
    __convertDOM: function (sel) {
        typeof sel == "string" && (sel = document.querySelector(sel));
        return sel;
    }, has: function (sel, cls) {
        sel = this.__convertDOM(sel);
        return sel.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
    }, add: function (sel, cls) {
        sel = this.__convertDOM(sel);
        if (!Class.has(sel, cls)) sel.className += " " + cls;
    }, remove: function (sel, cls) {
        sel = this.__convertDOM(sel);
        if (Class.has(sel, cls)) {
            var reg = new RegExp(cls, "g");
            sel.className = sel.className.replace(reg, "");
        }
    }, /*切换className*/ toggle: function (sel, cls) {
        sel = this.__convertDOM(sel);
        if (Class.has(sel, cls)) {
            Class.remove(sel, cls);
        } else {
            Class.add(sel, cls);
        }
    }
};
/*测试用例*/
Class.toggle("body", "testClass");
/*scss循环*/
          @for $i from 1 through length($数组) {
            $color: nth($数组, $i);
            &:nth-of-type(#{$i}) {
              color: $color;
              &:hover {
                color: white;
              }
            }
          }
        /*图片填充文字背景*/
        height: auto;
        width: auto;
        background: url(bg.png) no-repeat left center;
        background-origin: border-box;
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        /*fillcolor是Webkit内核私有属性哦 */



        /*渐变文字(仅谷歌内核浏览器支持)*/
        background: -webkit-linear-gradient(white, black);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;

      v-for="(item,$index) in items"
      :key="$index"
      :hover="hoverIndex==$index"
      :current="currentIndex==$index"
      @mouseover="hoverIndex=$index,autoPlay=false"
      @mouseout="hoverIndex=null,autoPlay=localAutoPlay"
      @click="currentIndex=$index"
      v-html="item.label"


    
  • {{item}}
  • // angularJS 用$loaction获取window.location信息
    // open http://host.com/base/index.html#!/a
    $location.absUrl() == 'http://host.com/base/index.html#!/a';
    $location.path() == '/a';
    $location.path('/foo');
    $location.absUrl() == 'http://host.com/base/index.html#!/foo';
    $location.search() == {};//search没东东的时候,返回空对象
    $location.search({a: 'b', c: true});
    $location.absUrl() == 'http://host.com/base/index.html#!/foo?a=b&c';
    $location.path('/new').search('x=y');//可以用字符串的方式更改search,每次设置search,都会覆盖之前的search
    $location.absUrl() == 'http://host.com/base/index.html#!/new?x=y';
    /*强制关闭不提示*/
    function CloseWebPage() {
        window.location.replace("about:blank");
    	window.opener = null;
    	window.open('', '_self');
    	window.close();
    }
        var space = {
            /*去掉字符串前后空格*/trimSpace: function (str) {
                str || (str = "");
                return str.replace(/(^\s*)|(\s*$)/g, "");
            }, /*去掉字符串中所有空格(包括中间空格)*/trimAllSpace: function (str) {
                str || (str = "");
                return str.replace(/\s+/g, "");
            }, /*去掉所有全角半角空格*/ trimAllWholeCornerSpace: function (str) {
                str || (str = "");
                return str.replace(/\ |\ /g, "");
            }, /*去掉所有全角半角 空格*/ trimAllWholeCornerCodeSpace: function (str) {
                str || (str = "");
                return this.trimAllWholeCornerSpace(str).replace(/ /g, "");
            }
        };
        /*转换为废代码文本(转换文本中的?<、>符号)*/
        var replaceLTandGT = function (s) {
            if (s == null || s == undefined) return "";
            return s.toString().replace(//g, ">");
        };
        /*边框虚线滚动动画特效*/
        .border-animate {
            background: linear-gradient(90deg, gray 60%, transparent 60%) repeat-x left top/10px 1px,
            linear-gradient(0deg, gray 60%, transparent 60%) repeat-y right top/1px 10px,
            linear-gradient(90deg, gray 60%, transparent 60%) repeat-x right bottom/10px 1px,
            linear-gradient(0deg, gray 60%, transparent 60%) repeat-y left bottom/1px 10px;
    
            animation: border-animate .382s infinite linear;
        }
    
        @keyframes border-animate {
            0% {
                background-position: left top, right top, right bottom, left bottom;
            }
            100% {
                background-position: left 10px top, right top 10px, right 10px bottom, left bottom 10px;
            }
        }
    var random = {
        /*获取两个数之间的随机小数(fixed是有效数字位数)*/
        getDecimal(a, b, fixed) {
            var num = Math.random() * (a - b) + b;
            if (fixed != undefined && fixed != null && fixed >= 0) {
                num = fixed === 0 ? Math.round(num) : parseFloat(num.toFixed(fixed));
            }
            return num;
        },
        /*获取两个数之间的随机整数*/
        getInteger(a, b) {
            return this.getDecimal(a, b, 1);
        },
        /*返回a到b且包含a和b的随机整数(其中a,b不能为负数)*/
        get(a, b) {
            if (arguments.length == 1) {
                (b = a, a = 0);
            } else {
                a < 0 && (a = 0);
                b < 0 && (b = 0);
                a = a || 0;
                b = b || 9;
            }
            return Math.round(Math.random() * b + a);
        },
        /*获取数组中的随机一个元素*/
        valueFromArray(arr) {
            if (arr && arr.length > 0) {
                return arr[random.get(arr.length - 1)];
            } else {
                return arr;
            }
        },
        /*获取数组中的随机多个元素组成的数组*/
        arrayFromArray(arr, data) {
            var tempArr = arr.concat();
            data.randomTotal || (data.randomTotal = 0);//0代表获取任意多个随机元素,>0代表获取randomTotal个随机元素
            data.startIndex || (data.startIndex = 0);//从数组开头随机的索引值
            data.startIndex < 0 && (data.startIndex = 0);
            data.endIndex || (data.endIndex = arr.length);//随机截止到尾部的索引值
            data.endIndex <= data.startIndex && (data.endIndex = data.startIndex + 1);
            data.endIndex > arr.length && (data.endIndex = arr.length);
            data.isContinue || (data.isContinue = false);//是否获取连续随机元素
            data.isRepeat || (data.isRepeat = false);//是否获取重复的元素
            if (data.isContinue) {
                var startIndex = data.randomTotal ? this.get(0, data.endIndex ? data.endIndex : tempArr.length - data.randomTotal) : this.get(0, tempArr.length);
                startIndex < data.startIndex && (startIndex = data.startIndex);
                var endIndex = data.randomTotal ? startIndex + data.randomTotal : this.get(startIndex, tempArr.length);
                endIndex > data.endIndex && (endIndex = data.endIndex);
                return tempArr.slice(startIndex, endIndex);
            } else {
                var newArr = [];
                for (var i = 0, len = data.randomTotal || tempArr.length; i < len; i++) {
                    var randomIndex = this.get(data.startIndex > tempArr.length ? tempArr.length - 1 : data.startIndex, data.endIndex > tempArr.length - 1 ? tempArr.length - 1 : data.endIndex);
                    newArr.push(tempArr[randomIndex]);
                    data.isRepeat || tempArr.splice(randomIndex, 1);
                }
                return newArr;
            }
        }
    };
    
    //测试用例
    console.log(random.arrayFromArray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], {
        randomTotal: 3,
        startIndex: 0,
        endIndex: 10,
        isContinue: true,
        isRepeat: false
    }));
    
    /*边框渐变*/
    border: 1px solid;
    border-image: -webkit-linear-gradient(-45deg, rgba(255, 255, 255, 0.3) 0%, rgba(255, 255, 255, 0) 100%) 1 1; /* Safari 5.1 - 6.0 */
    border-image: -o-linear-gradient(-45deg, rgba(255, 255, 255, 0.3) 0%, rgba(255, 255, 255, 0) 100%) 1 1; /* Opera 11.1 - 12.0 */
    border-image: -moz-linear-gradient(-45deg, rgba(255, 255, 255, 0.3) 0%, rgba(255, 255, 255, 0) 100%) 1 1; /* Firefox 3.6 - 15 */
    border-image: linear-gradient(-45deg, rgba(255, 255, 255, 0.3) 0%, rgba(255, 255, 255, 0) 100%) 1 1; /* 标准的语法(必须放在最后) */

     

    你可能感兴趣的:(Sg.js框架,Sg.js,PLUS)