博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

带字数限制提示的输入框效果

Posted on 2013-02-06 12:37  人生梦想起飞  阅读(1830)  评论(0编辑  收藏  举报

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>无标题文档</title>

<script src="jquery.js" type="text/javascript"></script>

</head>

<body>

<textarea name="s1" id="test" rows="5" cols="50" maxlength="10" id="test"></textarea>

<br>共可输入10字符,还剩 <span id="testtest"></span>个字符</font>

</body>

</html>

<script type="text/javascript">

$(function(){  

    $("#testtest").html(10);  

    document.getElementById("test").onpropertychange =document.getElementById("test").onkeyup= function(){   

                 var lenE = this.value.length;  

                 var tno = document.getElementById("testtest");

                 tno.innerHTML = 10  - lenE ;

                if (tno.innerHTML < 0) {   

                                var tmp = 0 ;

                                var cut = this.value.substring(0, 10);

                               for (var i=0; i<cut.length; i++){     

                                      tmp += /[\u4E00-\u9FA5\uF900-\uFA2D]/.test(cut.charAt(i)) ? 2 : 1;  

                                      if (tmp > 10) break;   

                 }        

                this.value = cut.substring(0, 10);

      }    

  }

})

</script>