获取输入文本字段AS3插入位置(X,Y)?
问题描述:
我需要让我的输入文本框插入符的位置。我并不需要设置的位置,我需要得到插入符号的当前位置。能不知道这一点,它的驾驶我疯了!
I need to get the position of the caret in my input textfield. I don't need to set the position, i need to get the current location of the caret. Can't figure this out and it's driving me crazy!
答
检查 Texfield.caretIndex 财产和 TextField.getCharBoundaries()方法的文档。它实际上是容易的,但它变得棘手时,该字段为空或下一个字符是一个空的/新行。
Check the Texfield.caretIndex property and TextField.getCharBoundaries() method in documentation. It's actually easy but it gets tricky when the field is empty or the next char is a empty/newline.
import flash.text.TextField;
import flash.text.TextFormat;
import flash.text.TextFieldType;
import flash.events.KeyboardEvent;
import flash.geom.Rectangle;
var t:TextField = new TextField();
t.x = t.y = 20;
t.width = 200;
t.height = 100;
t.multiline = t.wordWrap = t.border = true;
t.defaultTextFormat = new TextFormat('_sans',20);
t.type = TextFieldType.INPUT;
addChild(t);
stage.focus = t;
t.addEventListener(KeyboardEvent.KEY_DOWN,kd);
function kd(e:KeyboardEvent):void {
if (!e.ctrlKey) return;
var car:int = t.caretIndex;
var rect:Rectangle = t.getCharBoundaries(car);
if (rect == null) {
trace('caret:'+car,'need to calculate this possibility')
} else {
trace('caret:'+car,rect,'(relative to textfield)');
}
}