textbox如果設置TextMode="MultiLine"則它的MaxLength設置的值就無效;為了能達到像騰訊微薄、新浪微薄那樣的提示的效果(騰訊和新浪微薄文本框用到的應該是textarea),嘗試如果不考慮用鼠標操作粘貼、刪除textbox的內容,用jquery的keyup和keydown能實現,下面是實現的一個技巧,用到了js的計時器(當焦點在textbox中則“開啟”計時器,失去焦點則“關閉”計時器),很好的解決了鼠標操作粘貼、刪除textbox的內容不能改變字符個數的問題
首先在head標記中添加如下js代碼當然還要引用jquery.js,這里知道就好了!<script> |
02 | |
03 | vart =""; |
04 | functionmaxLimit() { |
05 | if($.trim($("#txtContent").val()).length > 140) { |
06 | $("#txtleft").text("已經超出"); |
07 | $("#LabelContent").text(($.trim($("#txtContent").val()).length) - 140); |
08 | } |
09 | else{ |
10 | $("#txtleft").text("還能輸入"); |
11 | $("#LabelContent").text(140 - ($.trim($("#txtContent").val()).length)); |
12 | } |
13 | } |
14 | |
15 | functionsetTimeouts() { |
16 | maxLimit(); |
17 | t = setTimeout("setTimeouts()", 1 * 10); |
18 | }; |
19 | |
20 | functionclearTimeouts() { |
21 | clearTimeout(t); |
22 | }; |
23 | |
24 | |
25 | $(document).ready(function() { |
26 | |
27 | //$("#txtContent").keyup(maxLimit); |
28 | //$("#txtContent").keydown(maxLimit); |
29 | $("#txtContent").bind("blur", clearTimeouts); |
30 | $("#txtContent").bind("focus", setTimeouts) |
31 | }); |
32 | |
33 | </script> |
<div> <asp:TextBoxID="txtContent"runat="server"Width="500px"TextMode="MultiLine"MaxLength="140" |
Height="100px"></a |