一般在前台页面会对文本框的字数要做限制,一种方法是提示超出多少个字,不让保存对文本;还有一种是自动截取,但是自动截取对于键盘操作是没有问题的,对于鼠标的复制粘帖会有一些问题。下面看下代码:
<script type="text/javascript" src="jquery-1.4.3.min.js"></script>
<script type="text/javascript" src="common.js"></script>
<body> <!-- 有用代码开始 --><!--//输入框输入长度限制改进2,此方法绑定在input,textarea的onfocus事件上,参数分别人:this, maxlength,显示剩余字数的span的id.--><textarea id="textarea_catch_ask" οnfοcus="fed_inputMaxLength(this,200,'catchask_con_counter_num')" style="width:300px;height:300px" ></textarea><div class="textarea_con_counter">还能输入<strong id="catchask_con_counter_num">200</strong>字</div><!--有用代码结束-->
</body>
common.js的代码:
//输入框输入长度限制改进2,此方法绑定在input,textarea的onfocus事件上,参数分别人:this, maxlength,显示剩余字数的span的id.
function fed_inputMaxLength(target,maxlength,counterId){if($(target).attr('fed_max_length')==null){$(target).attr('fed_max_length',maxlength);var counter = $('#'+counterId);if ($.browser.msie) { //IE浏览器$(target).unbind("propertychange").bind("propertychange", function(e) {e.preventDefault();textareaMaxProc1(target, maxlength);counter.html(maxlength-$(target).val().length);});target.attachEvent("onpropertychange", function(e) {//e.preventDefault();textareaMaxProc1(target, maxlength);counter.html(maxlength-$(target).val().length);});}else { //ff浏览器target.addEventListener("input",function(e) {e.preventDefault();textareaMaxProc1(target, maxlength);counter.html(maxlength-$(target).val().length);},false); }$('target').unbind("keypress").bind("keypress", function(event) {var code;if(typeof event.charCode =="number" ){ //charCode只在keypress事件后才包含值,此时keyCode可能有值也可能没有,Ie没有charCode属性。code = event.charCode;}else{code = event.keyCode;}if(code > 9 && !event.ctrlKey && $(target).val().length>=maxlength){event.preventDefault();}else if(event.ctrlKey && $(target).val().length>=maxlength && code==118){event.preventDefault();}});}
}function textareaMaxProc1(textArea, total){var max;max=total;if($(textArea).val().length > max){$(textArea).val($(textArea).val().substring(0,max));}
}
源码下载: http://download.csdn.net/download/shiyuezhong/4702027