通用代码积累

 
  

(function(win, doc, docEl) {
function setRem() {
var width = docEl.getBoundingClientRect().width;
var rem = width / 10;

win.rem = rem;
docEl.style.fontSize = rem + 'px';
}
setRem();

var remTimer;
win.addEventListener('resize', function() {
clearTimeout(remTimer);
remTimer = setTimeout(setRem, 300);
}, false);
})(window, document, document.documentElement)

Number.prototype.formatMoney = function (places, thousand, decimal) {
  places = !isNaN(places = Math.abs(places)) ? places : 2;
  thousand = thousand || ",";
  decimal = decimal || ".";
  var number = this,
  negative = number < 0 ? "-" : "",
  i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
  j = (j = i.length) > 3 ? j % 3 : 0;
  return negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
};


/*
* * 获取字符串的真实长度 * @method getStrLeng * @param string str 目标字符串 * @return int 真实的长度值 */ function getStrLeng(str){ var realLength = 0; var len = str.length; var charCode = -1; var cn=en=0; for(var i = 0; i < len; i++){ charCode = str.charCodeAt(i); if (charCode >= 0 && charCode <= 128) { realLength += 1; en+=1; }else{ realLength += 2; cn+=1; } } return realLength; } /** * 判断指定字符或数字是否存在于目标数组中 * @method in_array * @param needle str|number 目标字符串 * @param haystack str|int 目标数组 * @return bool bool true,false */ function inArray(needle, haystack) { if(typeof needle == 'string' || typeof needle == 'number'){ for(var i in haystack){ if(haystack[i] == needle){ return true; } } } return false; } /** * 获取文本中的html指定字符替换成字符实体 * @method htmlEncode * @param string text 目标文本 * @return text 返回替换后的文本 */ function htmlEncode(text) { return !text ? text : String(text).replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;"); } /** * 获取文本中的html指定字符实体替换成字符 * @method htmlDecode * @param string text 目标文本 * @return text 返回替换后的文本 */ function htmlDecode(text) { return !text ? text : String(text).replace(/&amp;/g, "&").replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&quot;/g, '"'); } /** * 对字符串进行去空格处理 * @method utilsTrim * @param string text 目标文本 * @return text 返回去空格后的文本 */ function utilsTrim(text) { if (typeof(text) == "string") { return text.replace(/^\s*|\s*$/g, ""); } else { return text; } } /** * 判断指定值是否为空 * @method utilsIsEmpty * @param string val 目标值 * @return bool bool true,false */ function utilsIsEmpty(val) { switch (typeof(val)) { case 'string': return utilsTrim(val).length == 0 ? true : false; break; case 'number': return val == 0; break; case 'object': return val == null; break; case 'array': return val.length == 0; break; default: return true; } } /** * 判断指定值是否是数值 * @method utilsIsNumber * @param string val 目标值 * @return bool bool true,false */ function utilsIsNumber(val) { var reg = /^[\d|\.|,]+$/; return reg.test(val); } /** * 判断指定值是否是数字整型 * @method utilsIsInt * @param string val 目标值 * @return bool bool true,false */ function utilsIsInt(val) { if (val == "") { return false; } var reg = /\D+/; return !reg.test(val); } /** * 判断指定值是否是邮箱格式 * @method utilsIsEmail * @param string email 目标邮箱 * @return bool bool true,false */ function utilsIsEmail(email) { var reg = /([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)/; return reg.test(email); } /** * 判断指定值是否是手机号格式 * @method utilsIsMobile * @param string mobile 目标手机号码 * @return bool bool true,false */ function utilsIsMobile(mobile) { var reg = /^1[2|3|4|5|6|7|8|9][0-9]{9}$/; return reg.test(mobile); } /** * 判断指定值是否是身份证号格式 * @method utilsIsIdNumber * @param string idnumber 目标身份证号 * @return bool bool true,false */ function utilsIsIdNumber(idnumber) { var reg = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/; return reg.test(idnumber); } /** * 判断指定值是否是银行卡卡号格式 * @method utilsIsBankCardNumber * @param string bankcardnumber 目标卡号 * @return bool bool true,false */ function utilsIsBankCardNumber(bankcardnumber) { var reg = /^(\d{16}|\d{18}|\d{19})$/; return reg.test(bankcardnumber); } /** * 判断指定值是否是汉字格式 * @method utilsIsChineseCharacters * @param string str 目标字符 * @return bool bool true,false */ function utilsIsChineseCharacters(str) { var reg = /^([\u4e00-\u9fa5]){2,20}$/; return reg.test(str); } /** * 银行卡格式输出,每4个字符进行空格 * @method bankCardNumberFormat * @param string value 目标卡号 * @return string 转换格式后的卡号 */ function bankCardNumberFormat(value) { var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, ''); var matches = v.match(/\d{4,19}/g); var match = matches && matches[0] || ''; var parts = []; for (i=0, len=match.length; i<len; i+=4) { parts.push(match.substring(i, i+4)); } if (parts.length) { return parts.join(' '); } else { return value; } } /** * 点击按钮触发秒数倒计时 * @method countDownSecondClickBtn * @param int secondtime 倒计时的描述 * @param string btnId 按钮的id属性 * @param string beforeBtnClickStr 按钮初始话内容 * @param string allowClickClass 允许重新触发的class * @param string forbidClickClass 禁止重新触发的class * @return null */ function countDownSecondClickBtn(secondtime, btnId, beforeBtnClickStr, allowClickClass, forbidClickClass ) { var btn = $('#'+btnId); var hander = setInterval(function () { if (time <= 0) { btn.attr("class",allowClickClass); btn.html(beforeClickStr); clearInterval(hander); }else{ btn.attr("class",forbidClickClass); btn.html(time--); } }, 1000); } /** * 判断是否是微信浏览器 * @method isWeixinBrowser * @return bool bool true,false */ function isWeixinBrowser() { var ua = navigator.userAgent.toLowerCase(); if ( ua.indexOf('micromessenger') != -1 ) { return true; }else{ return false; } } /** * 当前页面刷新 * @method refreshPage * @param int secondtime 倒计时的描述 * @param string btnId 按钮的id属性 * @param string beforeBtnClickStr 按钮初始话内容 * @param string allowClickClass 允许重新触发的class * @param string forbidClickClass 禁止重新触发的class * @return null */ function refreshPage() { var cur_url = window.location.href; var url_arr = cur_url.split('?'); if( isWeixinBrowser() ){ //微信内部的浏览器刷新 window.location.href = url_arr+"?j="+10000 * Math.random(); }else{ window.location.reload(); } return false; }

// "true"  => true
 392   // "false" => false
 393   // "null"  => null
 394   // "42"    => 42
 395   // "42.5"  => 42.5
 396   // JSON    => parse if valid
 397   // String  => self
 398 
 399   function deserializeValue(value) {
 400     var num
 401     try {
 402       return value ? value == "true" || (value == "false" ? false : value == "null" ? null : !isNaN(num = Number(value)) ? num : /^[\[\{]/.test(value) ? $.parseJSON(value) : value) : value
 403     } catch (e) {
 404       return value
 405     }
 406   }
 

 

@media only screen and (max-width:640px){html{font-size:100px;}}
@media only screen and (max-width:414px){html{font-size:64.6875px;}}
@media only screen and (max-width:375px){html{font-size:58.5938px;}}
@media only screen and (max-width:360px){html{font-size:56.25px;}}
@media only screen and (max-width:320px){html{font-size:50px;}}

 

/*! normalize.css v4.1.1 | MIT License | github.com/necolas/normalize.css */html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}body{margin:0}article,aside,details,figcaption,figure,footer,header,main,menu,nav,section,summary{display:block}
audio,canvas,progress,video{display:inline-block}audio:not([controls]){display:none;height:0}progress{vertical-align:baseline}template,[hidden]{display:none}
a{background-color:transparent;-webkit-text-decoration-skip:objects}a:active,a:hover{outline-width:0}abbr[title]{border-bottom:0;text-decoration:underline;text-decoration:underline dotted}
b,strong{font-weight:inherit}b,strong{font-weight:bolder}dfn{font-style:italic}h1{font-size:2em;margin:.67em 0}mark{background-color:#ff0;color:#000}small{font-size:80%}
sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-0.25em}sup{top:-0.5em}img{border-style:none}svg:not(:root){overflow:hidden}
code,kbd,pre,samp{font-family:monospace,monospace;font-size:1em}figure{margin:1em 40px}hr{box-sizing:content-box;height:0;overflow:visible}button,input,select,textarea{font:inherit;margin:0}
optgroup{font-weight:bold}button,input{overflow:visible}button,select{text-transform:none}button,html [type="button"],[type="reset"],[type="submit"]{-webkit-appearance:button}
button::-moz-focus-inner,[type="button"]::-moz-focus-inner,[type="reset"]::-moz-focus-inner,[type="submit"]::-moz-focus-inner{border-style:none;padding:0}
button:-moz-focusring,[type="button"]:-moz-focusring,[type="reset"]:-moz-focusring,[type="submit"]:-moz-focusring{outline:1px dotted ButtonText}
fieldset{border:1px solid #c0c0c0;margin:0 2px;padding:.35em .625em .75em}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal}
textarea{overflow:auto}[type="checkbox"],[type="radio"]{box-sizing:border-box;padding:0}[type="number"]::-webkit-inner-spin-button,[type="number"]::-webkit-outer-spin-button{height:auto}
[type="search"]{-webkit-appearance:textfield;outline-offset:-2px}[type="search"]::-webkit-search-cancel-button,[type="search"]::-webkit-search-decoration{-webkit-appearance:none}
::-webkit-input-placeholder{color:inherit;opacity:.54}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video{margin:0;padding:0;border:0;font-size:100%;font:inherit;vertical-align:baseline}
// 根据屏幕宽度控制字体大小
(function(doc, win) {
    var docEl = doc.documentElement,
        resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
        recalc = function() {
            var clientWidth = docEl.clientWidth;
            if (!clientWidth) return;
            docEl.style.fontSize = 26 * (clientWidth / 750) + 'px';
        };

    if (!doc.addEventListener) return;
    win.addEventListener(resizeEvt, recalc, false);
    doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);

 

//根据浏览器的宽自动分配body的字号
var clientWidth;
(function (doc, win) {
    
    var docEl = doc.documentElement,
        resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
        recalc = function () {
            // if (docEl.style.fontSize) return;
            clientWidth = docEl.clientWidth;
            //alert(clientWidth);
            clientWidth = clientWidth>750?750:clientWidth;
            clientWidth = clientWidth<320?320:clientWidth;
            if (!clientWidth) return;
            docEl.style.fontSize =100 * (clientWidth / 750) + 'px';
            if (document.body) {
                document.body.style.fontSize = docEl.style.fontSize;
            }
        };
    recalc();
    if (!doc.addEventListener) return;
    win.addEventListener(resizeEvt, recalc, false);
    doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);

 

(function (doc, win) {
    //取得html的引用
    var docEl = doc.documentElement,
        resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
        recalc = function () {
            var clientWidth = docEl.clientWidth;
            if (!clientWidth) return;
            clientWidth = (clientWidth > 768 )  ?  768 : clientWidth ;
            docEl.style.fontSize = 100 * (clientWidth / 375 ) + 'px';
        };
    if (!doc.addEventListener) return;
    win.addEventListener(resizeEvt, recalc, false);
    recalc();

})(document, window);

 

//designWidth:设计稿的实际宽度值,需要根据实际设置
//maxWidth:制作稿的最大宽度值,需要根据实际设置
//这段js的最后面有两个参数记得要设置,一个为设计稿实际宽度,一个为制作稿最大宽度,例如设计稿为750,最大宽度为750,则为(750,750)
(function(designWidth, maxWidth) {
    var doc = document,
    win = window,
    docEl = doc.documentElement,
    remStyle = document.createElement("style"),
    tid;

    function refreshRem() {
        var width = docEl.getBoundingClientRect().width;
        maxWidth = maxWidth || 540;
        width>maxWidth && (width=maxWidth);
        var rem = width * 100 / designWidth;
        remStyle.innerHTML = 'html{font-size:' + rem + 'px !important;}';
    }

    if (docEl.firstElementChild) {
        docEl.firstElementChild.appendChild(remStyle);
    } else {
        var wrap = doc.createElement("div");
        wrap.appendChild(remStyle);
        doc.write(wrap.innerHTML);
        wrap = null;
    }
    //要等 wiewport 设置好后才能执行 refreshRem,不然 refreshRem 会执行2次;
    refreshRem();

    win.addEventListener("resize", function() {
        clearTimeout(tid); //防止执行两次
        tid = setTimeout(refreshRem, 300);
    }, false);

    win.addEventListener("pageshow", function(e) {
        if (e.persisted) { // 浏览器后退的时候重新计算
            clearTimeout(tid);
            tid = setTimeout(refreshRem, 300);
        }
    }, false);

    if (doc.readyState === "complete") {
        doc.body.style.fontSize = "16px";
    } else {
        doc.addEventListener("DOMContentLoaded", function(e) {
            doc.body.style.fontSize = "16px";
        }, false);
    }
})(750, 750);

 

    (function(){
        var newFont = function(){
            // alert(window.innerWidth);
            var win = window.innerWidth > 640 ? 640 : window.innerWidth;
            var num = win/320;
            document.documentElement.style.fontSize = 16*num+'px';
        }
        newFont();
        window.onresize = newFont;
        window.jsAct = '';
        var pressX = 0, pressY = 0;
        document.addEventListener('touchmove',function(e){
             if (e.targetTouches.length == 1) {
                 var touch = event.targetTouches[0];
                 var spanY = touch.pageY - pressY;
                 // alert(spanY);
                 if (spanY > 0 && document.body.scrollTop <= 0) {
                     e.preventDefault();
                     // location.reload();
                     return false;
                 }
             }
        });
        document.addEventListener('touchstart', function(event) {
        // 如果这个元素的位置内只有一个手指的话
        if (event.targetTouches.length == 1) {
                var touch = event.targetTouches[0];
                // 把元素放在手指所在的位置
                pressX = touch.pageX;
                pressY = touch.pageY;
                // touchStart.value = pressX + ';' + pressY;
            }
        }, false);
    })();
    

 

(function flexible (window, document) {
  var docEl = document.documentElement
  var dpr = window.devicePixelRatio || 1

  // adjust body font size
  function setBodyFontSize () {
    if (document.body) {
      document.body.style.fontSize = '16px'
    } else {
      document.addEventListener('DOMContentLoaded', setBodyFontSize)
    }
  }
  setBodyFontSize()

  // set 1rem = viewWidth / 10
  function setRemUnit () {
    var rem = docEl.clientWidth / 10
    docEl.style.fontSize = rem + 'px'
  }

  setRemUnit()

  // reset rem unit on page resize
  window.addEventListener('resize', setRemUnit)
  window.addEventListener('pageshow', function (e) {
    if (e.persisted) {
      setRemUnit()
    }
  })

  // detect 0.5px supports
  if (dpr >= 2) {
    var fakeBody = document.createElement('body')
    var testElement = document.createElement('div')
    testElement.style.border = '.5px solid transparent'
    fakeBody.appendChild(testElement)
    docEl.appendChild(fakeBody)
    if (testElement.offsetHeight === 1) {
      docEl.classList.add('hairlines')
    }
    docEl.removeChild(fakeBody)
  }
}(window, document))

 

(function($) {
    /**
     * 对Jquery扩展方法
     */
    $.extend(jQuery,{
        /**
         * 从c参数中复制所有配置属性到o参数中
         * 
         * @param o 被复制的对象
         * @param c 要复制的对象
         * @param defaults 如果存在不同对象是,将该对象也复制到o参数中
         */
        apply:function(o, c, defaults) {
            if(defaults){
                $.apply(o, defaults);
            }
            if(o && c && typeof c === 'object'){
                for(var p in c){
                    o[p] = c[p];
                }
            }
            return o;
        },

        /**
         * 如果o参数对象没有该属性时,从c参数中复制所有配置属性到o参数中。
         * 
         * @param o 被复制的对象
         * @param c 要复制的对象
         */
        applyIf:function(o, c){
            if(o){
                for(var p in c){
                    if(!$.isDefined(o[p])){
                        o[p] = c[p];
                    }
                }
            }
            return o;
        },

        /**
         * 在一个数组中遍历调用方法,返回调用方法后的新数组,
         * <pre>
         *     $.invoke(Ext.query("p"), "getAttribute", "id");
         *  返回 [el1.getAttribute("id"), el2.getAttribute("id"), ..., elN.getAttribute("id")]
         * </pre>
         * 
         * @param arr 待调用方法的数组
         * @param methodName 要执行的方法名称
         */
        invoke : function(arr, methodName){
            var ret = [],
                args = Array.prototype.slice.call(arguments, 2);
            $.each(arr, function(i,v) {
                if (v && typeof v[methodName] == 'function') {
                    ret.push(v[methodName].apply(v, args));
                } else {
                    ret.push(undefined);
                }
            });
            return ret;
        },
        
        escapeRe : function(s) {
            return s.replace(/([-.*+?^${}()|[\]\/\\])/g, "\\$1");
        },
        
        /**
         * 重写某个类,当方法名相同时候会覆盖当前类的方法,当方法名不存在时,将会添加到类中,属性也一样
         * 
         * <pre>
         *     $.override(MyClass, {
         *        newMethod1: function(){
         *            // etc.
         *        },
         *        newMethod2: function(foo){
         *            // etc.
         *        }
         *    });
         * </pre>
         * 
         * @param origclass 要重写的类
         * @param overrides 重写方法或者属性的对象
         */
        override : function(origclass, overrides){
            if(overrides){
                var p = origclass.prototype;
                $.apply(p, overrides);
                if(overrides.hasOwnProperty('toString')){
                    p.toString = overrides.toString;
                }
            }
        },
        
        /**
         * 判断一个值或对象是否为空
         * 
         * @param v 要判断的值
         * @param allowBlank true 为允许字符串为''值
         */
        isEmpty: function(v, allowBlank){
            return v === null || v === undefined || (($.isArray(v) && !v.length)) || (!allowBlank ? v === '' : false);
        },

        /**
         * 判断一个值或对象是否不为空
         * 
         * @param v 要判断的值
         * @param allowBlank true 为允许字符串为''值
         */
        isNotEmpty : function(v, allowBlank){
            return !$.isEmpty(v, allowBlank);
        },

        /**
         * 判断一个值是否日期类(Date)型
         * 
         * @param v 要判断的值
         */
        isDate : function(v){
            return toString.apply(v) === '[object Date]';
        },
        
        /**
         * 判断一个值是否对象([object:object])类型
         * 
         * @param v 要判断的值
         */
        isObject : function(v){
            return !!v && Object.prototype.toString.call(v) === '[object Object]';
        },

        /**
         * 判断一个值是否String类型
         * 
         * @param v 要判断的值
         */
        isString : function(v){
            return typeof v === 'string';
        },

        /**
         * 判断一个值是否Boolean类型
         * 
         * @param v 要判断的值
         */
        isBoolean : function(v) {
            return typeof v === 'boolean';
        },
        
        /**
         * 判断一个值是否HTML元素
         * 
         * @param v 要判断的值
         */
        isElement : function(v) {
            return v ? !!v.tagName : false;
        },

        /**
         * 判断一个值是否已经定义
         * 
         * @param v 要判断的值
         */
        isDefined : function(v){
            return typeof v !== 'undefined';
        },
        
        /**
         * 判断一个HTML是否为隐藏状态
         * 
         * @param v 要判断的值
         */
        isHide:function(el){
            return $(el).css("display") === "none" || $(el).css("visibility") === "hidden";
        },
        
        /**
         * 判断一个值是否是整型,如果是返回当前值,如果不是返回defaultValue参数的值
         * 
         * @param v 要判断的值
         * @param defaultValue 如果不是整型将要返回的值,
         * @param replaceStr 要删除某些String类型的字符
         */
        number:function(v,defaultValue,replaceStr){

            if (v == "auto") {
                v = 0;
            }

            if ($.isString(v) && v.length > 0) {
                v = v.replaces(replaceStr,"").replace(" ","");
            }

            if ($.isEmpty(v) || $.isArray(v) || $.isBoolean(v)) {
                v = NaN;
            }

            v = Number(v);

            return isNaN(v) ? defaultValue : v;
        },
        
        /**
         * 如果v参数值为空,返回defaultValue参数值。
         * 
         * @param v 值
         * @param defaultValue 如果值为空将要返回的值
         * @param allowBlank true表示允许值为''值
         */
        value : function(v, defaultValue, allowBlank){
            return $.isEmpty(v, allowBlank) ? defaultValue : v;
        },

        /**
         * 如果value参数值超过指定长度,截断字符串并添加一个省略号("…")到结束的位置中
         * 
         * <pre>
         * $.ellipsis("123456789",5)
         * 返回:12345...
         * </pre>
         * 
         * @param value 值
         * @param len 要截取的长度
         * @param word 省略字符,默认为...
         * 
         * @return String
         */
        ellipsis : function(value, len, word) {
            if (value && value.length > len) {
                if (word) {
                    var vs = value.substr(0, len - 2),
                        index = Math.max(vs.lastIndexOf(' '), vs.lastIndexOf('.'), vs.lastIndexOf('!'), vs.lastIndexOf('?'));
                    if (index == -1 || index < (len - 15)) {
                        return value.substr(0, len - 3) + "...";
                    } else {
                        return vs.substr(0, index) + "...";
                    }
                } else {
                    return value.substr(0, len - 3) + "...";
                }
            }
            return value;
        },
        /**
         * 将json符串转换为json 对象
         * 
         * @param json json 字符串
         * @param useNative 是否使用浏览器常规的转换方式,true表示是,false表示不是,默认为:false
         * 
         * @returns Object
         */
        parseJSON:function(json,useNative) {
            if ($.isObject(json)) {
                return json;
            }
            if (useNative) {
                return JSON.parse(json);
            }
            return eval("(" + json + ')');
        },
        /**
         * 空方法
         */
        emptyFn:function () {}
    });

    /**
     * 对JS Function类扩展
     */
    $.applyIf(Function.prototype, {
        /**
         * 对某个参数创建一个拦截器方法,如果拦截器方法返回false时,将不会调用要执行的方法,如果返回true时调用要执行的方法
         * <pre>
         *     var sayHi = function(name){
         *        alert('Hi, ' + name);
         *    }
         *    
         *    sayHi('Fred'); // alerts "Hi, Fred"
         *    
         *    // 创建拦截器
         *    // 如果name==Brian后在执行sayHi方法
         *    var sayHiToFriend = sayHi.createInterceptor(function(name){
         *        return name == 'Brian';
         *    });
         *    
         *    sayHiToFriend('Fred');  // no alert
         *    sayHiToFriend('Brian'); alerts "Hi, Brian"
         * </pre>
         * 
         * @param fcn 拦截器方法
         * @param scope 拦截器方法的作用域
         */
        createInterceptor : function(fcn, scope){
            var method = this;
            return !$.isFunction(fcn) ?
                    this :
                    function() {
                        var me = this,
                            args = arguments;
                        fcn.target = me;
                        fcn.method = method;
                        return (fcn.apply(scope || $ , args) !== false) ?
                                method.apply(me, args) :
                                null;
                    };
        },

        /**
         * 通过arguments[0], arguments[1], arguments[2],创建一个callback方法来将参数传递到要执行的方法中
         * 
         * <pre>
         *     var sayHi = function(name){
         *        alert('Hi, ' + name);
         *    }
         *    
         *    
         *    sayHi.createCallback('Fred') //alerts "Hi, Fred"
         * </pre>
         */
        createCallback : function(){
            var args = arguments,
                method = this;
            return function() {
                return method.apply($, args);
            };
        },

        /**
         * 创建一个委托回调,将obj作为当前方法的作用域去执行方法体里的代码,可以通过args参数来对该方法的要接受的参数进行传递
         * 
         * <pre>
         *     var sayHi = function(name){
         *        alert('Hi, ' + name);
         *    }
         *    
         *    
         *    sayHi.createDelegate(window,["Fred"]) //alerts "Hi, Fred"
         * </pre>
         * 
         * @param obj 作用域
         * @param args 传递的参数
         * @param appendArgs 如果为true args参数将不会覆盖原有方法的参数值
         */
        createDelegate : function(obj, args, appendArgs){
            var method = this,slice = Array.prototype.slice;
            return function() {
                var callArgs = args || arguments;
                if (appendArgs === true){
                    callArgs = slice.call(arguments, 0);
                    callArgs = callArgs.concat(args);
                }else if ($.isNumeric(appendArgs)){
                    callArgs = slice.call(arguments, 0);
                    var applyArgs = [appendArgs, 0].concat(args);
                    slice.apply(callArgs, applyArgs);
                }

                return method.apply(obj || $, callArgs);
            };
        },

        /**
         * 类似setTimeout方法,该方法执行时间的同时,可以把方法的作用域以及参数传递的方法体中
         * 
         * <pre>
         * var sayHi = function(name){
         *        alert('Hi, ' + name);
         *    }
         *    
         *    // 执行方法:
         *    sayHi('Fred');
         *    
         *    // 两秒中后执行方法:
         *    sayHi.defer(2000, this, ['Fred']);
         * </pre>
         * 
         * @param millis 等待多用毫秒执行该方法
         * @param obj 作用域
         * @param args 要传递的参数
         * @param appendArgs  如果为true args参数将不会覆盖原有方法的参数值
         * 
         */
        defer : function(millis, obj, args,  appendArgs){
            var fn = this.createDelegate(obj, args, appendArgs);
            if(millis > 0){
                return setTimeout(fn, millis);
            }
            fn();
            return 0;
        }
    });

    /**
     * 重写String类属性
     */
    $.applyIf(String.prototype, {
        /**
         * 去除空格
         * @returns string
         */
        trim : function () {
            return this.replace(/(^\s*)|(\s*$)/g, "");
        },
        /**
         * 通过占位符格式化字符串
         * <pre>
         * "1{0}3{1}5".messageFormat("2","4");
         * 返回:12345
         * </pre>
         * 
         */
        messageFormat : function(){
            var args = [];

            for(var i = 0 ; i < arguments.length ; i++){
                args.push(arguments[i]);
            }

            return this.replace(/\{(\d+)\}/g, function(m, i){
                return args[i];
            });
        },

        /**
        *
        * 通过字符串数组替换字符串,返回替换后的字符串,
        *
        * @param array 替换字符串数组
        * @param arg 要替换的值
        *
        * @return String
        **/
        replaces:function(array,arg) {
            var temp = this.toString();

            if ($.isNotEmpty(array) && $.isArray(array)) {
                for (var i = 0; i < array.length; i++) {
                    var str = array[i];
                    if ($.isString(str)) {
                        temp = temp.replace(array[i],arg);
                    }
                }
            }

            return temp;
        },

        /**
         * 如果value等于当前值,返回当前值,反则返回other参数的值
         */
        toggle:function(value, other){
            return this.toString() == value ? other : value;
        },

        /**
         * 如果当前值的长度小于size参数的长度是,将当前值从左边开始补位.
         * 
         * <pre>
         *     "123".leftPad(5,"00");
         * 返回:"00123"
         * </pre>
         * 
         * @param size 要判断的长度
         * @param ch 要不为的字符
         */
        leftPad : function (size, ch) {
            var val = this.toString();
            var result = String(val);
            if(!ch) {
                ch = " ";
            }
            while (result.length < size) {
                result = ch + result;
            }
            return result;
        },

        /**
         * 如果当前值超过指定长度,截断字符串并添加一个省略号("…")到结束的位置中
         * 
         * <pre>
         * "123456789".ellipsis(5)
         * 返回:12345...
         * </pre>
         * 
         * @param len 要截取的长度
         * @param word 省略号,默认为 "..."
         */
        ellipsis:function(len, word){
            return $.ellipsis(this.toString(),len,word);
        },

        /**
         * 将当前值转换为boolean类型
         * 
         * <pre>
         *     "1".booleanValue() 返回:true
         *  "0".booleanValue() 返回false
         *  "true".booleanValue() 返回 true
         *  "false".booleanValue() 返回 false
         *  "abc".booleanValue("abc") 返回 true
         *  "abc".booleanValue("aaa") 返回 false
         * </pre>
         * 
         * @param compareValue 自定义比对值
         */
        booleanValue:function(compareValue){
            var value = this.toString();
            return $.isNotEmpty(value) && (value === "true" || value === "1" || ($.isNotEmpty(compareValue) || value == compareValue));
        },
        
        /**
         * 将当前值转换为数字类型
         * 
         * @returns number
         */
        numberValue:function() {
            var value = this.toString();
            return $.isNotEmpty(value) ? value * 1 : value;
        }
    });

    /**
     * 重写 Date 对象, 添加 format 函数
     */
    $.applyIf(Date.prototype,{
        /**
         * 
         * 格式化日志
         * 
         * @param format 格式化字符串
         * 
         * @returns string
         */
        format : function (format) { //author: meizz 
            var o = {
                "M+": this.getMonth() + 1, //月份 
                "d+": this.getDate(), //
                "h+": this.getHours(), //小时 
                "m+": this.getMinutes(), //
                "s+": this.getSeconds(), //
                "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
                "S": this.getMilliseconds() //毫秒 
            };
            if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(format)) format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return format;
        }
    });
    
    /**
     * 扩张数组属性
     */
    $.applyIf(Array.prototype, {

        /**
         * 在当前数组中遍历寻找o对象,如果相等返回当前所在数组的未知,返回返回-1
         * 
         * @o 要遍历寻找的对象
         * @from 从第几位开始遍历
         */
        indexOf : function(o, from){
            var len = this.length;
            from = from || 0;
            from += (from < 0) ? len : 0;
            for (; from < len; ++from){
                if(this[from] === o){
                    return from;
                }
            }
            return -1;
        },

        /**
         * 从当前数组中删除对象
         * 
         * @param o 要删除的对象
         */
        remove : function(o){
            var index = this.indexOf(o);
            if(index != -1){
                this.splice(index, 1);
            }
            return this;
        },
        /**
         * 将数组添加到本数组中
         * 
         * @param o 数组
         */
        addAll:function(o) {
            if ($.isEmpty(o) && !$.isArray(o) && o.length < 0) {
                return ;
            }

            for(var i = 0; i < o.length; i++) {
                this.push(o[i]);
            }
        }
    });

 

if (!NeuF) var NeuF = {};
NeuF.ScrollPage = function (obj, options, callback) {
    var _defaultOptions = { delay: 500, marginBottom: 100 }; //默认配置:延迟时间delay和滚动条距离底部距离marginBottom
    options = $.extend(_defaultOptions, options);
    this.isScrolling = false; //是否在滚动
    this.oriPos = 0; //原始位置
    this.curPos = 0; //当前位置
    var me = this; //顶层
    var $obj = (typeof obj == "string") ? $("#" + obj) : $(obj);
    //绑定滚动事件
    $obj.scroll(function (ev) {
        me.curPos = $obj.scrollTop();
        if ($(window).height() + $(window).scrollTop() >= $(document.body).height() - options.marginBottom) {
            if (me.isScrolling == true) return;
            me.isScrolling = true;
            setTimeout(function () { me.isScrolling = false; }, options.delay);   //重复触发间隔毫秒
            if (typeof callback == "function") callback.call(null, me.curPos - me.oriPos);
        };
        me.oriPos = me.curPos;
    });
};

下载通用代码js:
downloadFile(filePath: any) {
    this.meetingService.downloadFile(filePath, rtv => {
      if (rtv) {
        let _blob = new Blob([rtv]);
        let _filename = filePath.substring(filePath.lastIndexOf('_') + 1);
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          window.navigator.msSaveOrOpenBlob(_blob, _filename);
        } else {
          let _link = document.createElement('a');
          let _url = window.URL.createObjectURL(_blob);
          document.body.appendChild(_link);
          _link.setAttribute('style', 'display:none');
          _link.href = _url;
          _link.download = _filename;
          _link.click();
          window.URL.revokeObjectURL(_url);
          _link.remove();
        }
      } else {
        alert('下载失败,请稍后重试!');
      }
    });
  }
 
  

 

 
 

转载于:https://www.cnblogs.com/sybboy/p/9371809.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值