快速背景。我有一系列可编辑的文本区域,我希望能够在单击按钮时添加变量。
如果我单击按钮,textarea失去焦点,所以我无法编码我需要将变量添加到哪个textarea。任何人都可以想到一种方法来保持对文本框的关注,插入变量然后允许用户继续打字。
我不确定这是否部分或完全可能,但我们非常感谢任何帮助。我一直在玩setFocus函数试图让它工作没有成功。
以下是我的代码片段:
public function addFirstName(myText:string):void{
myText = myText + "<<firstname>>";
}
<mx:TextArea id="txt1" change="text1=txt1.text" text="{text3}" editable="true"/>
<mx:TextArea id="txt2" change="text2=txt2.text" text="{text2}" editable="true"/>
<mx:Button label="Insert First Name" click="addFirstName(focusedtextarea)"/>
它的焦点部分区域我坚持
提前致谢!
答案 0 :(得分:1)
使用focus out事件编写一些代码来存储需要更改的文本区域。概念上是这样的:
var textAreaToBeChanged : TextArea;
protected function onTextAreaLoseFocus(event:FocusEvent):void{
// I'm pretty sure Target is the right property to use here; but didn't test
textAreaToBeChanged = target;
}
稍后在MXML中添加事件监听器。:
<mx:TextArea id="txt1" change="text1=txt1.text" text="{text3}" editable="true" focusOut="{onTextAreaLoseFocus(event)}"/>
<mx:TextArea id="txt2" change="text2=txt2.text" text="{text2}" editable="true" focusOut="{onTextAreaLoseFocus(event)}"/>
答案 1 :(得分:0)
排序!
public var textAreaToBeChanged : Object;
public var textposition:int
//when leaving focus on a textbox, record the textarea and text position. If a button is clicked to add a variable, it needs to be added at this position
protected function onTextAreaLoseFocus(event:FocusEvent):void{
textAreaToBeChanged = event.target;
textposition = textAreaToBeChanged.caretIndex;
}
//split the text from the recent textbox at the position the cursor has just been. The restructure the text with the firstname variable in the middle.
public function addFirstName():void{
var firstbit:String = textAreaToBeChanged.text.substr(0,textposition);
var myString:String = firstbit;
myString = myString + firstnameVar;
var lastbit:String = textAreaToBeChanged.text.substr(textposition);
myString = myString + lastbit;
textAreaToBeChanged.text = myString;
//set the focus back to the textarea.
textAreaToBeChanged.setFocus();
//place the cursor after the variable we just added.
textAreaToBeChanged.setSelection(textposition + firstnameVar.length, textposition + firstnameVar.length);
}
和MXML:
<mx:TextArea id="txt1" change="text1=txt1.text" text="{text3}" editable="true" focusOut="{onTextAreaLoseFocus(event)}"/>
<mx:TextArea id="txt2" change="text2=txt2.text" text="{text2}" editable="true" focusOut="{onTextAreaLoseFocus(event)}"/>
<mx:Button label="Insert First Name" click="addFirstName()"/>