-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinputMaxLen.html
More file actions
61 lines (61 loc) · 2.1 KB
/
inputMaxLen.html
File metadata and controls
61 lines (61 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>限制输入框的字符个数</title>
</head>
<body>
<textarea id="textarea"></textarea>
<textarea id="origin"></textarea>
<script type="text/javascript" src="jquery-2.1.4.js"></script>
<script type="text/javascript">
//jQuery方法
jQuery.fn.maxLength = function(max){
this.each(function(){
var type = this.tagName.toLowerCase();
var inputType = this.type ? this.type.toLowerCase():null;
if(type == 'input' && inputType == 'text' || inputType == 'password'){
this.maxLength = max;
}else if(type == 'textarea'){
this.onkeypress=function(e){
var ob = e||event;
var keyCode = ob.keyCode;
console.log('keyCode:',keyCode)
var hasSelection = document.selection?document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;
return !(this.value.length >= max && (keyCode > 32 || keyCode == 32||keyCode == 0 ||keyCode == 13)&&!ob.ctrlKey && !ob.altKey && !hasSelection);
}
this.onkeyup = function(){
if(this.value.length > max){
this.value = this.value.substring(0,max);
}
}
}
});
}
//不依赖于jQuery的方法
function Max($doms,max){
$doms.each(function(){
var type = this.tagName.toLowerCase();
var inputType = this.type ? this.type.toLowerCase():null;
if(type == 'input' && inputType == 'text' || inputType == 'password'){
this.maxLength = max;
}else if(type == 'textarea'){
this.onkeypress=function(e){
var ob = e||event;
var keyCode = ob.keyCode;
var hasSelection = document.selection?document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;
return !(this.value.length >= max && (keyCode >32 || keyCode == 32||keyCode == 0 ||keyCode == 13)&&!ob.ctrlKey && !ob.altKey && !hasSelection);
}
this.onkeyup = function(){
if(this.value.length > max){
this.value = this.value.substring(0,max);
}
}
}
});
}
$('#textarea').maxLength(10);//jQuery方法
Max($('#origin'),10);
</script>
</body>
</html>