input 和 textarea 输入框最大文字限制插件
/* input 和 textarea 最大文字限定插件 |
02 |
* 修改版, 一个中文表示1一个字, 一个英文半个字; |
03 |
* TextLimit - jQuery plugin for counting and limiting characters for input and textarea fields |
04 |
* |
05 |
* pass '-1' as speed if you don't want the char-deletion effect. (don't just put 0) |
06 |
* Example: jQuery("Textarea").textlimit('span.counter',256) |
07 |
* |
08 |
* $Version: 2009.07.25 +r2 |
09 |
* Copyright (c) 2009 Yair Even-Or |
10 |
* vsync.design@gmail.com |
11 |
*/ |
12 |
; |
13 |
String.prototype.getBytes = function () { |
14 |
var cArr = this.match(/[^\x00-\xff]/ig); |
15 |
return this.length + (cArr == null ? 0 : cArr.length); |
16 |
}; |
17 |
(function(jQuery) { |
18 |
jQuery.fn.textlimit=function(counter_el, thelimit, speed) { |
19 |
var charDelSpeed = speed || 15; |
20 |
var toggleCharDel = speed != -1; |
21 |
var toggleTrim = true; |
22 |
var that = this[0]; |
23 |
var isCtrl = false; |
24 |
updateCounter(); |
25 |
|
26 |
function updateCounter(){ |
27 |
if(typeof that == "object") |
28 |
jQuery(counter_el).text(thelimit - Math.ceil(that.value.getBytes()/2)); |
29 |
}; |
30 |
|
31 |
this.keydown (function(e){ |
32 |
if(e.which == 17) isCtrl = true; |
33 |
var ctrl_a = (e.which == 65 && isCtrl == true) ? true : false; // detect and allow CTRL + A selects all. |
34 |
var ctrl_v = (e.which == 86 && isCtrl == true) ? true : false; // detect and allow CTRL + V paste. |
35 |
// 8 is 'backspace' and 46 is 'delete' |
36 |
if( this.value.length >= thelimit && e.which != '8' && e.which != '46' && ctrl_a == false && ctrl_v == false) |
37 |
e.preventDefault(); |
38 |
}) |
39 |
.keyup (function(e){ |
40 |
updateCounter(); |
41 |
if(e.which == 17) |
42 |
isCtrl=false; |
43 |
|
44 |
if( this.value.length >= thelimit && toggleTrim ){ |
45 |
if(toggleCharDel){ |
46 |
// first, trim the text a bit so the char trimming won't take forever |
47 |
// Also check if there are more than 10 extra chars, then trim. just in case. |
48 |
if ( (this.value.length - thelimit) > 10 ) |
49 |
that.value = that.value.substr(0,thelimit+100); |
50 |
var init = setInterval |
51 |
( |
52 |
function(){ |
53 |
if( that.value.length <= thelimit ){ |
54 |
init = clearInterval(init); updateCounter() |
55 |
} |
56 |
else{ |
57 |
// deleting extra chars (one by one) |
58 |
that.value = that.value.substring(0,that.value.length-1); jQuery(counter_el).text(Math.ceil(that.value.getBytes()/2)); |
59 |
} |
60 |
} ,charDelSpeed |
61 |
); |
62 |
} |
63 |
else this.value = that.value.substr(0,thelimit); |
64 |
} |
65 |
}); |
66 |
|
67 |
}; |
68 |
})(jQuery); |
浙公网安备 33010602011771号