AS3在TextField CaretIndex位置插入和删除字符

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AS3在TextField CaretIndex位置插入和删除字符相关的知识,希望对你有一定的参考价值。

This code gets the current caretIndex in the textfield and then inserts the specified string at that point. The caretIndex position is then updated using setSelection, ready for the next insertion. This was developed to be used with an on-screen keyboard (for entering text into a textfield when the user is in fullscreen mode). The backspace button is intended to function in the same manner as pressing the delete key on your keyboard.
  1. // This code assumes you have an input textfield on the stage
  2. // called 'inputTxt' and two movieclips called 'onInsertBtnClick' and 'onBackspaceBtnClick'.
  3. // Here we are just inserting incrementing number as an example.
  4.  
  5. import flash.events.MouseEvent;
  6. import flash.text.TextField;
  7.  
  8. var num:int = 1;
  9.  
  10. insertBtn.addEventListener(MouseEvent.CLICK, onInsertBtnClick);
  11. insertBtn.buttonMode = true;
  12. backspaceBtn.addEventListener(MouseEvent.CLICK, onBackspaceBtnClick);
  13. backspaceBtn.buttonMode = true;
  14.  
  15. function onInsertBtnClick(e:MouseEvent):void {
  16. var charToInsert:String = String(num);
  17. var tf:TextField = inputTxt;
  18. var initialText:String = tf.text;
  19. var ci:int = tf.caretIndex;
  20. var newText:String = initialText.substring(0, ci) + charToInsert + initialText.substring(ci, initialText.length)
  21. tf.text = newText;
  22. tf.setSelection(ci+(charToInsert.length), ci+(charToInsert.length));
  23. num++;
  24. stage.focus = tf;
  25. }
  26.  
  27. function onBackspaceBtnClick(e:MouseEvent):void {
  28. var tf:TextField = inputTxt;
  29. var initialText:String = tf.text;
  30. var ci:int = tf.caretIndex;
  31. if (tf.text != "") {
  32. var newText:String = initialText.substring(0, ci-1) + initialText.substring(ci, initialText.length);
  33. tf.text = newText;
  34. tf.setSelection(ci-1, ci-1);
  35. }
  36. stage.focus = tf;
  37. }

以上是关于AS3在TextField CaretIndex位置插入和删除字符的主要内容,如果未能解决你的问题,请参考以下文章

AS3里【TextField】于【TextArea】有啥区别?

AS3 TextField和样式表示例(在ActionScript中创建)

ActionScript 3 AS3 TextField和StyleSheet示例(在ActionScript中创建)

textfield不会清楚,as3

ActionScript 3 AS3 TextHandle Util - TextField变得简单

AS3 自定义 TextField 文本正在其 textWidth 之外绘制