为TextArea添加maxLength属性,在网上找了好多方法,可是虽然实现了限制长度,但是总是长按键盘或者粘贴的时候就会先显示上边然后再消失,总是闪烁一下,好纠结,于是就写了一个这个,基本上已经不闪烁了,谷歌,IE、搜狗高速兼容已测试,没问题~~~后续将整理出来一个JQuery插件来使用。
1 <html xmlns="http://www.w3.org/1999/xhtml">
2 <head>
3 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
4 <title></title>
5 <script>
6
7 function doKeyPress(obj, evt) {
8 maxLength = obj.getAttribute("maxlength");
9 var e = window.event ? event.keyCode : evt.which;
10 if ((e == 32) || (e == 13) || (e > 47)) {
11 //IE
12 if (maxLength && (obj.value.length > maxLength - 1)) {
13 if (window.event) {
14 var oTR = obj.document.selection.createRange();
15 if (oTR.text.length > 0) {
16
17 } else {
18 window.event.returnValue = null;
19 }
20 }
21 else {
22 evt.cancelDefault;
23 return false;
24 }
25 }
26 }
27 }
28
29 function doKeyUp(obj) {
30 maxLength = obj.getAttribute("maxlength");
31 if (maxLength && obj.value.length > maxLength) {
32 obj.value = obj.value.substr(0, maxLength);
33 }
34 sr = obj.getAttribute("ShowLength");
35 if (sr) {
36 // alert((maxLength - obj.value.length));
37 document.getElementById(sr).innerHTML = "可填 <em style='color:#CC3300;'>" + (maxLength - obj.value.length) + "</em> 字";
38 }
39 }
40
41 // 取消默认行为和创建一个新的粘贴程序
42 function doPaste(obj) {
43 maxLength = obj.getAttribute("maxlength");
44 if (maxLength) {
45 var detect = navigator.userAgent.toLowerCase();
46 if ((window.event) && (detect.indexOf("safari") + 1 == 0)) {
47 //IE
48 var oTR = obj.document.selection.createRange();
49 var iInsertLength = maxLength - obj.value.length + oTR.text.length;
50 try {
51 var sData = window.clipboardData.getData("Text").substr(0, iInsertLength);
52 oTR.text = sData;
53 }
54 catch (err) {
55 }
56 if (window.event) {
57 //IE
58 window.event.returnValue = false;
59 }
60 else {
61 //not IE
62 obj.value = obj.value.substr(0, maxLength);
63 return false;
64 }
65 }
66 }
67 }
68 </script>
69 </head>
70 <body>
71 <textarea rows="6" cols="50" maxlength="10" onkeyup="doKeyUp(this)" onkeypress="doKeyPress(this,event)"
72 onpaste="doPaste(this)" showlength="mes"></textarea>
73 <br />
74 <span id="mes"></span>
75 </body>
76 </html>