• 一个前端框架应该有的一些公共函数


     一、防止ie浏览器按backspace回退页面

    //防止后退返回页面,如果非文本框、密码框、文本域控件,或控件非可用装填,则禁用后退按键
    var ua=navigator.userAgent.toLowerCase(); 
    var isIE=ua.indexOf("msie")>-1;
    window.document.onkeydown =function(e){
        var e = e;
        var obj;        //事件源
        var t;            //控件类型
        var keyCode;    //按键ascii码
        if(isIE){
            e = event || window.event;
            keyCode = e.keyCode;
        }else{
            keyCode = e.keyCode || e.which;
            if(keyCode==undefined||keyCode==null||keyCode==''){
                keyCode=String.fromCharCode(e.charCode);
            }
        }
        obj = e.target || e.srcElement; //获取事件源 
        t = obj.type || obj.getAttribute('type'); 
        if (e.keyCode==8 && (obj.readOnly || obj.disabled || (t != "password" && t != "text" && t != "textarea" && obj.tagName!=='INPUT'))) {
            return false;
        }
    };

    二、获取页面传参 

    // 获取参数
    var name = window.location.search; //获取?后面的字符串
    function getUrlParam(name) { var urlArr = [],urlObj={}; name = decodeURI(name); urlArr=name.substring(1).split('&'); for(var i =0;i<urlArr.length;i++){ var valueArr=urlArr[i].split('='); urlObj[valueArr[0]]=valueArr[1]; } return urlObj; }

    三、加载动画(避免重复点击机制),初始化ajax(以jquery为例)

     1 jQuery.bootstrapLoading = {
     2     start: function (options) {
     3         var defaults = {
     4             opacity: 1,
     5             //loading页面透明度
     6             backgroundColor: "rgba(0,0,0,0.3)",
     7             //loading页面背景色
     8             borderColor: "#bbb",
     9             //提示边框颜色
    10             borderWidth: 0,
    11             //提示边框宽度
    12             borderStyle: "solid",
    13             //提示边框样式
    14             loadingTips: "",
    15             //提示文本
    16             TipsColor: "#666",
    17             //提示颜色
    18             delayTime: 1000,
    19             //页面加载完成后,加载页面渐出速度
    20             zindex: 99999999,
    21             //loading页面层次
    22             sleep: 0,
    23             //设置挂起,等于0时则无需挂起
    24              '150px',
    25             height: '165px',
    26         }
    27         var options = $.extend(defaults, options);
    28 
    29         //获取页面宽高
    30         var _PageHeight = document.documentElement.clientHeight,
    31         _PageWidth = document.documentElement.clientWidth;
    32         //获取页面路径
    33         var baseUrl = window.document.location.protocol + "//" + window.document.location.host + "/";
    34           var shortenedUrl = window.document.location.href.replace(baseUrl, "").replace(////g, "/").replace("//", "/");
    35           if(shortenedUrl.startsWith("/")){
    36               shortenedUrl = shortenedUrl.substring(1);
    37           }
    38           if(shortenedUrl.indexOf("web/")==0){
    39               baseUrl = baseUrl + shortenedUrl.substring(0, shortenedUrl.indexOf("/"));
    40           }
    41         //在页面未加载完毕之前显示的loading Html自定义内容
    42         var _LoadingHtml = '<div id="loadingPage" style="position:fixed;left:0;top:0;_position: absolute;100%;height:' + _PageHeight + 'px;background:' + options.backgroundColor + ';opacity:' + options.opacity + ';filter:alpha(opacity=' + options.opacity * 100 + ');z-index:' + options.zindex + 
    43         ';"><div id="loadingTips" class="loadingTips" style="position: absolute; cursor1: wait; border-color:' + options.borderColor + 
    44         ';background-position:50%;  '+options.width+';height:'+options.height+';border-style:' + options.borderStyle + ';border-' + options.borderWidth + 'px; line-height:80px; padding: 15px;border-radius:10px;  background: url('+baseUrl+'/images/loading.gif) no-repeat center; color:' + options.TipsColor + ';font-size:20px;">' 
    45         + options.loadingTips + '</div></div>';
    46 
    47         //呈现loading效果
    48         $("body").append(_LoadingHtml);
    49         //获取loading提示框宽高
    50         var _LoadingTipsH = document.getElementById("loadingTips").clientHeight,
    51         _LoadingTipsW = document.getElementById("loadingTips").clientWidth;
    52 
    53         //计算距离,让loading提示框保持在屏幕上下左右居中
    54         var _LoadingTop = _PageHeight > _LoadingTipsH ? (_PageHeight - _LoadingTipsH) / 2 : 0,
    55         _LoadingLeft = _PageWidth > _LoadingTipsW ? (_PageWidth - _LoadingTipsW) / 2 : 0;
    56 
    57         $(".loadingTips").css({
    58             "left": _LoadingLeft + "px",
    59             "top": _LoadingTop + "px"
    60         });
    61 
    62         //监听页面加载状态
    63         // document.onreadystatechange = PageLoaded;
    64 
    65         //当页面加载完成后执行
    66         // function PageLoaded() {
    67         //     if (document.readyState == "complete") {
    68         //         var loadingMask = $('#loadingPage');
    69 
    70         //         setTimeout(function () {
    71         //             loadingMask.animate({
    72         //                 "opacity": 0
    73         //             },
    74         //             options.delayTime,
    75         //             function () {
    76         //                 $(this).hide();
    77 
    78         //             });
    79 
    80         //         },
    81         //         options.sleep);
    82 
    83         //     }
    84         // }
    85     },
    86     end: function () {
    87         $("#loadingPage").remove();
    88     }
    89 }
    90 //初始化ajax
    91 $.ajaxSetup({
    92     beforeSend:function(xhr){
    93         $.bootstrapLoading.start();
    94     },
    95         complete: function () {
    96             $.bootstrapLoading.end();
    97         }
    98 });

    4、时间格式化

    Date.prototype.format=function(fmt) {         
        var o = {         
        "M+" : this.getMonth()+1, //月份         
        "d+" : this.getDate(), //
        "h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //小时         
        "H+" : this.getHours(), //小时         
        "m+" : this.getMinutes(), //
        "s+" : this.getSeconds(), //
        "q+" : Math.floor((this.getMonth()+3)/3), //季度         
        "S" : this.getMilliseconds() //毫秒         
        };         
        var week = {         
        "0" : "/u65e5",         
        "1" : "/u4e00",         
        "2" : "/u4e8c",         
        "3" : "/u4e09",         
        "4" : "/u56db",         
        "5" : "/u4e94",         
        "6" : "/u516d"        
        };         
        if(/(y+)/.test(fmt)){         
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));         
        }         
        if(/(E+)/.test(fmt)){         
            fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "/u661f/u671f" : "/u5468") : "")+week[this.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;         
    } 
    
    function getDate(strDate){
        if(strDate && strDate!=""){
            var date = eval('new Date(' + strDate.replace(/d+(?=-[^-]+$)/, function (a) { return parseInt(a, 10) - 1; }).match(/d+/g) + ')');
            return date;
        }
        return undefined;
    }
    
    function formatDate(date, fmt){
        var format = fmt || "yyyy-MM-dd hh:mm:ss";
        if(date instanceof Date){
            return date.format(format);
        }else if(typeof date == 'string'){
            var d = getDate(date);
            if(d){
                return d.format(format);
            }
            return '';
        }else{
            return date;
        }
    }

     5、格式化数据(树状结构)

     1 TreeDataFormat = {
     2     format : function(conf) {
     3         var idField, textField, parentField, iconClsField;
     4         idField = conf.idField ||  'id';
     5         textField = conf.textField || 'text';
     6         parentField = conf.parentField || 'pid';
     7         iconClsField = conf.iconClsField || 'iconCls';
     8         data = conf.data
     9         var i, l, treeData = [], tmpMap = [];
    10         for (i = 0, l = data.length; i < l; i++) {
    11             data[i]['id'] = data[i][idField];
    12             data[i]['text'] = data[i][textField];
    13             data[i]['pid'] = data[i][parentField];
    14             data[i]['iconCls'] = data[i][iconClsField] || 'anticon icon-nav';
    15             data[i]['children'] = [];
    16             tmpMap[data[i][idField]] = data[i];
    17         }
    18         for (i = 0, l = data.length; i < l; i++) {
    19             if (tmpMap[data[i][parentField]] && data[i][idField] != data[i][parentField]) {
    20                 if (!tmpMap[data[i][parentField]]['children'])
    21                     tmpMap[data[i][parentField]]['children'] = [];
    22                 data[i][parentField]
    23                 data[i]['text'] = data[i][textField];
    24                 tmpMap[data[i][parentField]]['children'].push(data[i]);
    25             } else {
    26                 data[i]['text'] = data[i][textField];
    27                 treeData.push(data[i]);
    28             }
    29         }
    30         return treeData;
    31     },
    32     getChildrenByPid:function(treeData, pidField, pid, result){
    33         result = result || [];
    34         for (var i = 0; i < treeData.length; i++) {
    35             if (treeData[i][pidField] === pid)
    36                 result.push(treeData[i]);
    37             else {
    38                 if (treeData[i].hasOwnProperty("children")) {
    39                     result = this.getChildrenByPid(treeData[i].children, pidField, pid, result);
    40                 }
    41             }
    42         }
    43         return result;
    44     }    
    45 }
  • 相关阅读:
    eclipse rcp 获取工程项目路径
    Eclipse RCP中添加第三方jar包的办法
    eclipse content assist 代码提示功能失效解决办法
    lwuit更改字体大小
    lwuit调整滚动条灵敏度值
    AWTEvent
    IE7 IE6去掉关闭提示框的解决方案
    jQuery多库共存最优解决方案
    电子商务网站 数据库产品表设计方案
    javascript操作cookie
  • 原文地址:https://www.cnblogs.com/cutone/p/7125507.html
Copyright © 2020-2023  润新知