问题描述
||
快速背景。我有一系列可编辑的文本区域,我希望能够在其中单击按钮添加一个变量。
如果单击按钮,则文本区域失去焦点,因此我无法编写将变量添加到哪个文本区域的代码。谁能想到一种专注于文本框,插入变量然后允许用户进行键入的方法。
我不确定这是部分实现还是完全实现,但是任何帮助将不胜感激。我一直在尝试使用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)\"/>
它是我专注的文本区域部分
提前致谢!
解决方法
使用聚焦事件编写一些代码,以存储需要更改的文本区域。概念上是这样的:
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)}\"/>
, 排序!
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()\"/>