欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

项目中用到的小功能代码

程序员文章站 2022-04-29 16:44:01
...

cookie,阻止IOS底部拖动,截取地址栏参数,检测特殊字符,身份证号,银行卡号,手机号,移动端meta,

 

cookie :  移动端+PC端

1         var Cookie={Get:function(a){var d,b=document.cookie.split("; "),c=[];for(i=0;i<b.length;i++)d=b[i].split("="),c[d[0]]=unescape(d[1]);return a?c[a]:c},Set:function(a,b,c,d,e,f){var g,h;return a&&b?""==a||""==b?!1:(c&&(/^[0-9]+$/.test(c)?(g=new Date,c=new Date(g.getTime()+1e3*c).toGMTString()):/^wed, \d{2} \w{3} \d{4} \d{2}\:\d{2}\:\d{2} GMT$/.test(c)||(c=void 0)),h=a+"="+escape(b)+";"+(c?" expires="+c+";":"")+(d?"path="+d+";":"")+(e?"domain="+e+";":"")+(f&&0!=f?"secure":""),h.length<4096?(document.cookie=h,!0):!1):!1},Del:function(a,b,c){return a?""==a?!1:this.Get(a)?(document.cookie=a+"=;"+(b?"path="+b+";":"")+(c?"domain="+c+";":"")+"expires=Thu, 01-Jan-1970 00:00:01 GMT;",!0):!1:!1}},Cache=function(){var storage,api={},pre="NetCQ_",win=window,doc=win.document,localStorageName="localStorage",globalStorageName="globalStorage",JsonToStr=function(a){var c,b=[];if("string"==typeof a)return'"'+a.replace(/([\'\"\\])/g,"\\$1").replace(/(\n)/g,"\\n").replace(/(\r)/g,"\\r").replace(/(\t)/g,"\\t")+'"';if("undefined"==typeof a)return"undefined";if("object"==typeof a){if(null===a)return"null";if(a.sort){for(c=0;c<a.length;c++)b.push(JsonToStr(a[c]));b="["+b.join()+"]"}else{for(c in a)b.push('"'+c+'":'+JsonToStr(a[c]));b="{"+b.join()+"}"}return b}return a.toString()};return api.set=function(){},api.get=function(){},api.remove=function(){},api.clear=function(){},localStorageName in win&&win[localStorageName]?(storage=win[localStorageName],api.set=function(a,b){"object"==typeof b?storage.setItem(pre+a,JsonToStr(b)):storage.setItem(pre+a,b)},api.get=function(key){var _v,_cache=storage.getItem(pre+key)||"";try{_v=eval("("+_cache+")")}catch(e){_v=_cache}return _v},api.clear=function(a){a?storage.removeItem(pre+a):storage.clear()}):globalStorageName in win&&win[globalStorageName]?(storage=win[globalStorageName][win.location.hostname],api.set=function(a,b){"object"==typeof b?storage[pre+a]=JsonToStr(b):storage[a]=b},api.get=function(key){var _v,_cache=storage[pre+key].value||"";try{_v=eval("("+_cache+")")}catch(e){_v=_cache}return _v},api.clear=function(a){if(a)delete storage[pre+a];else for(var a in storage)delete storage[a]}):(api.set=function(a,b){Cookie.Set(pre+a,b)},api.get=function(a){return Cookie.Get(pre+a)},api.clear=function(a){var b,c;if(a)Cookie.Del(pre+a);else if(b=document.cookie.match(/[^ =;]+(?=\=)/g))for(c=b.length;c--;)document.cookie=b[c]+"=0;expires="+new Date(0).toUTCString()}),api}();
2            

  用法:

 Cache.set("flag",1); 
 Cache.get("flag");
Cache.clear();

 

判断是否运行在微信端:

function Is_weixn(){  
    var ua = navigator.userAgent.toLowerCase();  
    return (ua.match(/MicroMessenger/i)=="micromessenger");
}

 

阻止IOS端 底部拖动:

 1 //阻止IOS底部拖动
 2     function noscroll(){
 3         var content = document.querySelector('.content') || null;
 4         var startY;
 5         
 6         if(content){
 7             content.addEventListener('touchstart', function (e) {
 8             startY = e.touches[0].clientY;
 9         });
10         
11             content.addEventListener('touchmove', function (e) {
12                 // 高位表示向上滚动
13                 // 底位表示向下滚动
14                 // 1容许 0禁止
15                 var status = '11';
16                 var ele = this;
17             
18                 var currentY = e.touches[0].clientY;
19             
20                 if (ele.scrollTop === 0) {
21                     // 如果内容小于容器则同时禁止上下滚动
22                     status = ele.offsetHeight >= ele.scrollHeight ? '00' : '01';
23                 } else if (ele.scrollTop + ele.offsetHeight >= ele.scrollHeight) {
24                     // 已经滚到底部了只能向上滚动
25                     status = '10';
26                 }
27             
28                 if (status != '11') {
29                     // 判断当前的滚动方向
30                     var direction = currentY - startY > 0 ? '10' : '01';
31                     // 操作方向和当前允许状态求与运算,运算结果为0,就说明不允许该方向滚动,则禁止默认事件,阻止滚动
32                     if (!(parseInt(status, 2) & parseInt(direction, 2))) {
33                         e.preventDefault();
34                     }
35                 }
36             });
37         }        
38     }
39     

 

截取地址栏?后的参数对:

 1 var getUrlVars = function() {
 2       var vars = [],
 3            hash;
 4       var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
 5       for (var i = 0; i < hashes.length; i++) {
 6            hash = hashes[i].split('=');
 7            vars.push(hash[0]);
 8            vars[hash[0]] = hash[1];
 9        }
10        return vars;
11     }

 

检测是否包含特殊字符:

1 function containSpecial(s)      
2     {      
3       var containSpecial = RegExp(/[(\ )(\~)(\!)(\@)(\#)(\$)(\%)(\^)(\&)(\*)(\()(\))(\-)(\_)(\+)(\=)(\[)(\])(\{)(\})(\|)(\\)(\;)(\:)(\')(\")(\,)(\.)(\/)(\<)(\>)(\?)]/);      
4       return ( containSpecial.test(s) );      
5      } 

 

身份证号校验:

 function IdentityCodeValid(code) {
        var city={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江 ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北 ",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"* ",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"*",71:"*",81:"香港",82:"澳门",91:"国外 "};
        var tip = "";
        var pass= true;
        if(!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)){
            tip = "身份证号格式错误";
            pass = false;
        }
       else if(!city[code.substr(0,2)]){
            tip = "地址编码错误";
            pass = false;
        }
        else{
            //18位身份证需要验证最后一位校验位
            if(code.length == 18){
                code = code.split('');
                //∑(ai×Wi)(mod 11)
                //加权因子
                var factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
                //校验位
                var parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
                var sum = 0;
                var ai = 0;
                var wi = 0;
                for (var i = 0; i < 17; i++)
                {
                    ai = code[i];
                    wi = factor[i];
                    sum += ai * wi;
                }
                var last = parity[sum % 11];
                if(parity[sum % 11] != code[17]){
                    tip = "校验位错误";
                    pass =false;
                }
            }
        }
        return pass;
    }

 

手机号模式匹配:

1 /^1(3|4|5|7|8)\d{9}$/.test(mobile)

 

银行卡格式输入:

<input οnkeyup="this.value=this.value.replace(/(\d{4})(?=[^\s])/,'$1 ');" type="number" maxlength="23" />

 

适配移动端视口:

<!--移动端视口-->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, minimal-ui">
<!--iphone允许全屏模式浏览-->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta content="yes" name="apple-touch-fullscreen">
<!--忽略电话号码识别-->
<meta name="format-detection" content="telephone=no" />
<!--忽略邮箱识别-->
<meta content="email=no" name="format-detection" />
<!--iphone中safari顶端的状态条的样式-->
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<!--禁止百度转码-->
<meta http-equiv="Cache-Control" content="no-siteapp" />
<!--添加到主屏后的标题-->
<meta name="apple-mobile-web-app-title" content="标题">

小功能代码先到这里,部分代码来源于网络,如有侵权,请告之删除。