<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE> New Document </TITLE> <script type="text/javascript" src="jquery-1.4.2.min.js"></script> </HEAD> <BODY> <div> <textarea id="txtPrizeNote" runat="server" height="74px" width="480px" maxlength="10" style="width: 480px; height: 74px; float: left"></textarea> <span style="color: Red;">*</span><br /> 剩余字数:<span id="showmsg" style="color: red"></span> </div> </BODY> </HTML> <script type="text/javascript"> //返回val的字节长度 function getByteLen(val) { var len = 0; for (var i = 0; i < val.length; i++) { if (val[i].match(/[^\x00-\xff]/ig) != null) //全角 len += 2; else len += 1; } return len; } //返回val在规定字节长度max内的值 function getByteVal(val, max) { var returnValue = ''; var byteValLen = 0; for (var i = 0; i < val.length; i++) { if (val[i].match(/[^\x00-\xff]/ig) != null) byteValLen += 2; else byteValLen += 1; if (byteValLen > max) break; returnValue += val[i]; } return returnValue; } $(function() { var _area = $('textarea#txtPrizeNote'); var _info = _area.next(); var _max = _area.attr('maxlength'); var _val; _area.bind('keyup change', function() { //绑定keyup和change事件 if (_info.find('span').size() < 1) {//避免每次弹起都会插入一条提示信息 _info.append(_max); } _val = $(this).val(); _cur = getByteLen(_val); if (_cur == 0) {//当默认值长度为0时,可输入数为默认maxlength值 _info.text(_max); } else if (_cur < _max) {//当默认值小于限制数时,可输入数为max-cur _info.text(_max - _cur); } else {//当默认值大于等于限制数时 _info.text(0); $(this).val(getByteVal(_val,_max)); //截取指定字节长度内的值 } }); }); </script>
引自:http://www.jb51.net/article/25001.htm