龙博3.0β源码SVN地址http://linb.googlecode.com/svn/trunk/jsLinb3.0
下载龙博3.0β源码包!    下载龙博3.0教程-入门篇 pdf 版!
返回列表 回复 发帖

动态限制输入框的最大长度

跨浏览器的情况下,限制textarea输入框中文字的长度是一件不容易的事情。你需要至少考虑3点:
1.通过键盘输入字符;
2.通过paste输入(control+v 或 右键菜单);
3.通过拖拽输入文字;

在longboo中,可以用以下思路(通过同步和异步的处理)来达到动态限制文字输入的目的:
  1. Class('App', 'linb.Com',{
  2.     Instance:{
  3.         autoDestroy:true,
  4.         iniComponents:function(){
  5.             // [[code created by jsLinb UI Builder
  6.             var host=this, children=[], append=function(child){children.push(child.get(0))};

  7.             append((new linb.UI.Input)
  8.                 .host(host,"input555")
  9.                 .setLeft(100)
  10.                 .setTop(80)
  11.                 .setHeight(100)
  12.                 .setMultiLines(true)
  13.                 .setDynCheck(true)
  14.                 .onChange("_input555_onChange")
  15.                 .beforeKeypress("_input555_bk")
  16.             );

  17.             return children;
  18.             // ]]code created by jsLinb UI Builder
  19.         },
  20.         // 同步:防止用键盘直接敲入
  21.         _input555_bk:function(profile, caret, key, control, shift, alt) {
  22.             if(key.length==1){
  23.                 if(control && (key=='c'||key=='x'||key=='a'))
  24.                     return true;

  25.                 var len=profile.boxing().getUIValue().length - (caret[1]-caret[0]);
  26.                 if (len >= 10)
  27.                     return false;
  28.             }
  29.         },
  30.         // 异步:防止用paste或drop的方式输入
  31.         _input555_onChange:function (profile, oldValue, newValue) {
  32.             if (newValue.length > 10)
  33.                 profile.boxing().setUIValue(newValue.substr(0,10),true);
  34.         }
  35.     }
  36. });
复制代码
尊重彼此感受,善待体验工具,时时不忘召唤自己。
对于multilines=false的 (对应html input type="text" or type="password"),只需要用

setMaxlength(10)即可。

对于multilines=true的 (对应html input type="textarea"),必须要用以上方法。
尊重彼此感受,善待体验工具,时时不忘召唤自己。
返回列表