JS简单实用小功能(二)

一、限制字符串长度

通过“maxlength ”限制:<input type="text" name="lname" maxlength="5" /><br />
通过“JavaScript事件 ”限制:<input type="text" data-length='5' id='limitLength' data-model='Ch' name="lname"/><br />
 1    window.onload = function () {
 2             var limitLength = document.getElementById("limitLength"), //获取限制对象
 3                 clearNonumber = function (tThis) { //清除数字
 4                     var _v = tThis.value,
 5                         _vLen = _v.length,
 6                         dataLength = tThis.getAttribute("data-length"), //获取长度属性
 7                         dataModel = tThis.getAttribute("data-model"),
 8                         subLen = dataLength;
 9                     if (_vLen > dataLength) tThis.value = _v.substr(0, subLen); //判断长度
10                     if (remainingCharacters) {
11                         self.showRemainingCharacters(!_vLen ? dataLength : (_vLen >
12                             dataLength ? 0 : dataLength - _vLen), remainingCharacters);
13                     }
14                 };
15             limitLength.onfocus = function () { //获取焦点事件
16                 clearNonumber(this);
17             }
18             limitLength.onkeyup = function () { //键盘事件
19                 clearNonumber(this);
20             }
21             limitLength.onblur = function () { //失去焦点事件
22                 clearNonumber(this);
23             }
24         };

二、密码强度识别

<h2>密码强度实时验证</h2>
<input id="passwordStrength" data-hint='请输入密码' type="password"> <span id="showStrength"></span>
 1 window.onload = function(){
 2         function setCss(_this, cssOption){//设置样式
 3             if ( !_this || _this.nodeType === 3 || _this.nodeType === 8 || !_this.style ) {
 4                 return;
 5             }
 6             for(var cs in cssOption){
 7                 _this.style[cs] = cssOption[cs];
 8             }
 9             return _this;
10         }
11 
12         function trim(chars){//去除字符串左右两边的空格
13             return (chars || "").replace(/^(\s|\u00A0)+|(\s|\u00A0)+$/g, "" );
14         }
15 
16         function passwordStrength(passwordStrength, showStrength){
17             var self = this;
18             /*字符权重:
19              数字1,字母2 ,其他字符为3
20              当密码长度小于6为不符合标准,
21              长度大=6强度小于10,强度弱
22              ,长度大=6 强度>=10 <15,强度中,
23              长度大=6 强度>=15 强*/
24             passwordStrength.onkeyup = function(){
25                 var _color = ["red", "yellow", "orange", "green"],
26                         msgs = ["密码太短","弱","中","强"],
27                         _strength= 0,
28                         _v = trim(passwordStrength.value)
29                 _vL = _v.length,
30                         i = 0;
31 
32                 var charStrength = function(char){//计算单个字符强度
33                     if (char>=48 && char <=57){ //数字
34                         return 1;
35                     }
36                     if (char>=97 && char <=122) {//小写
37                         return 2;
38                     }else{
39                         return 3; //特殊字符
40                     }
41                 }
42 
43                 if(_vL < 6){//计算模式
44                     showStrength.innerText = msgs[0];
45                     setCss(showStrength, {
46                         "color":_color[0]
47                     })
48                 }else{
49                     for( ; i < _vL ; i++){
50                         _strength+=charStrength(_v.toLocaleLowerCase().charCodeAt(i));
51                     }
52                     if(_strength < 10){
53                         showStrength.innerText = msgs[1];
54                         setCss(showStrength, {
55                             "color":_color[1]
56                         })
57                     }
58                     if(_strength >= 10 && _strength < 15){
59                         showStrength.innerText = msgs[2];
60                         setCss(showStrength, {
61                             "color":_color[2]
62                         })
63                     }
64                     if(_strength >= 15){
65                         showStrength.innerText = msgs[3];
66                         setCss(showStrength, {
67                             "color":_color[3]
68                         })
69                     }
70                 }
71             }
72         }
73         passwordStrength(
74                 document.getElementById("passwordStrength"),
75                 document.getElementById("showStrength"));
76     };

三、回车提交

<input type="text" id="enterSubmit" value="回车提交">
 1     window.onload = function(){
 2         document.getElementById("enterSubmit").onkeyup = function(e){
 3             e = e || window.event;
 4             var keycode = e.keyCode || e.which ||e.charCode;
 5             if(keycode === 13){
 6                 alert("回车提交成功");
 7             }
 8 
 9         }
10     };

四、常见验证

<h2>常见的验证规则</h2>
<p><input type="text" value='姓名验证'  data-reg='Chinese' data-smsg='通过√' data-emsg='请输入中文' id='regUser' data-tmsg='msgU' /><span id='msgU'></span></p>
<p><input type="text" value='邮箱验证'  data-reg='email' data-smsg='通过√' data-emsg='请输入邮箱' id='regEmail' data-tmsg='msgE' /><span id='msgE'></span></p>
<p><input type="text" value='电话验证'  data-reg='phone' data-smsg='通过√' data-emsg='请输入电话' id='regPhone' data-tmsg='msgP' /><span id='msgP'></span></p>
<p><input type="text" value='带小数位的数字验证'  data-reg='decimalNumber' data-smsg='通过√' data-emsg='请输入小数数字' id='regNumber' data-tmsg='msgN' /><span id='msgN'></span></p>
 1   window.onload = function(){
 2         var getRegular = function(rstr){
 3                 var regData={};//正则数据存储域
 4                 regData.rtrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g;// 去除空格的正则
 5                 regData.Chinese = /[\u4e00-\u9fa5]/g;//中文
 6                 regData.nonumber = /\D/g;//数字
 7                 regData.nochinese = /[^\u4e00-\u9fa5]/g;//非中文
 8                 regData.email = /^\s*[a-zA-Z0-9]+(([\._\-]?)[a-zA-Z0-9]+)*@[a-zA-Z0-9]+([_\-][a-zA-Z0-9]+)*(\.[a-zA-Z0-9]+([_\-][a-zA-Z0-9]+)*)+\s*$/;//邮件
 9                 regData.phone = /^(([0\+]\d{2,3}-)?(0\d{2,3})-)(\d{7,8})(-(\d{3,})){0,}$/;//电话
10                 regData.decimalNumber = /^\d+(\.\d+)+$/;//带小数位的数字
11                 regData.htmlTags = /<[\/\!]*[^<>]*>/ig;//html
12 
13                 return regData[rstr];
14 
15             },
16             forElementArr = function(_elementArr, callBack){
17                 var arr =_elementArr,
18                         self = this
19                         ;
20 
21                 if(!(_elementArr instanceof Array)) {
22                     arr = [_elementArr];
23                 };
24                 for(var i= 0,arrLen = arr.length ;i<arrLen;i++){
25                     var arrI = arr[i];
26                     if(typeof arrI == "string"){
27                         arrI = self.getElement(arrI);
28                     }
29                     callBack && callBack(i, arrI);
30                 }
31             },
32             verification = function(str, reg){
33                 return getRegular(reg).test(str);
34             },
35             setCss = function(_this, cssOption){
36                 if ( !_this || _this.nodeType === 3 || _this.nodeType === 8 || !_this.style ) {
37                     return;
38                 }
39                 for(var cs in cssOption){
40                     _this.style[cs] = cssOption[cs];
41                 }
42                 return _this;
43             };
44 
45         forElementArr([
46             document.getElementById("regUser"),
47             document.getElementById("regEmail"),
48             document.getElementById("regPhone"),
49             document.getElementById("regNumber")
50         ], function(index, _this){
51 
52             _this.onkeyup = function(){
53                 var _v = this.value.replace( /^(\s|\u00A0)+|(\s|\u00A0)+$/g, "" ),//获取被处理的元素值
54                         _reg = this.getAttribute("data-reg"),//获取正则
55                         __reg = _reg.indexOf(",") > 0 ? _reg.split(","): [_reg],//如果含有“,”则将其转换成多数组
56                         _regLen = __reg.length,//数组长度
57                         _emsg = this.getAttribute("data-emsg"),//错误信息显示
58                         _smsg = this.getAttribute("data-smsg"),//通过信息显示
59                         _target = document.getElementById(this.getAttribute("data-tmsg")),//获取显示信息的元素
60                         i = 0;
61                 for(; i < _regLen ; i++){
62                     if(!verification(_v, __reg[i])){
63                         _target.innerHTML = _emsg ;
64                         setCss(_target, {
65                             "color":"red"
66                         })
67                         return;
68                     }
69                 }
70                 _target.innerHTML = _smsg ;
71                 setCss(_target, {
72                     "color":"green"
73                 })
74             }
75         });
76     };

五、单选

<h2>判断单选框是否选中</h2>
<input type="radio" name='sex' id='sexMan' checked="checked">男 <br />
<input type="radio" name='sex' id='sexWoman'>女
 1     window.onload = function(){
 2         var sexMan = document.getElementById("sexMan"),
 3                 sexWoman = document.getElementById("sexWoman");
 4         if(sexMan.checked){
 5             console.log("sexMan 被选中")
 6         }else{
 7             console.log("sexMan 未被选中")
 8         }
 9 
10         if(sexWoman.checked){
11             console.log("sexWoman 被选中")
12         }else{
13             console.log("sexWoman 未被选中")
14         }
15     };

猜你喜欢

转载自www.cnblogs.com/HopeInTheDark/p/11460076.html