该文档指出,如果要在文本字段中写入任何内容之前更改文本的格式以分配新的defaultTextFormat。否则,设置新格式将改变当前选择。
下面的解决方案通过将焦点放在文本字段上进行工作,所以当点击按钮时,文本字段仍然具有焦点。如果存在当前选择,则选择将根据按下哪个按钮而改变为蓝色或红色。如果没有选择,则应用新的defaultTextFormat,而不更改以前的defaultTextFormats,因为应用新格式时文本字段仍然具有焦点。
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.text.TextFormat;
import flash.events.MouseEvent;
import flash.events.FocusEvent;
public class ChangeTextColor extends Sprite
{
private var field:TextField;
private var redButton:Sprite;
private var blueButton:Sprite;
public function ChangeTextColor()
{
init();
}
//Initialize
private function init():void
{
//Create Text Field
field = new TextField();
field.type = TextFieldType.INPUT;
field.border = true;
field.x = field.y = 10;
addChild(field);
//Retain Focus On TextField
field.addEventListener(FocusEvent.FOCUS_OUT, fieldFocusOutHandler);
//Create Button
redButton = createButton(10, 120, 200, 20, 0xFF0000);
blueButton = createButton(10, 150, 200, 20, 0x0000FF);
}
//Create Button Method
private function createButton(x:uint, y:uint, width:uint, height:uint, color:uint):Sprite
{
var resultSprite:Sprite = new Sprite();
resultSprite.graphics.beginFill(color);
resultSprite.graphics.drawRect(0, 0, width, height);
resultSprite.graphics.endFill();
resultSprite.addEventListener(MouseEvent.CLICK, mouseClickEventHandler);
resultSprite.x = x;
resultSprite.y = y;
addChild(resultSprite);
return resultSprite;
}
//Apply Text Format
private function changeTextFormatColor(color:uint):void
{
var format:TextFormat = new TextFormat();
format.color = color;
//Change Format Of Selection Or Set Default Format
if (field.selectionBeginIndex != field.selectionEndIndex)
field.setTextFormat(format, field.selectionBeginIndex, field.selectionEndIndex);
else
field.defaultTextFormat = format;
}
//Maintain Focus Of TextField When Color buttons Are Clicked
private function fieldFocusOutHandler(evt:FocusEvent):void
{
stage.focus = evt.currentTarget as TextField;
}
//Button Click Event Handler
private function mouseClickEventHandler(evt:MouseEvent):void
{
switch (evt.currentTarget)
{
case redButton: trace("red clicked");
changeTextFormatColor(0xFF0000);
break;
case blueButton: trace("blue clicked");
changeTextFormatColor(0x0000FF);
}
}
}
}
另外,如果你在你的程序中的其他按钮,不涉及文本字段,并应使文本字段点击时失去重心,只是删除fieldFocusOutHandler功能和地点stage.focus =领域;在buttonClickHandler方法中。如果这是一个问题,您也可以保留并调整fieldFocusOutHandler函数。
嗨,感谢您的回复,但这不是我真的很想。我不想改变整个textarea的fontcolor。 要在textarea的部分设置不同的字体,我必须使用setTextFormat(objTextFormat,beginIndex,endIndex)。但在写之前,我没有beginIndex和endIndex,所以我不能这样做。我已经编辑了我的问题,请检查一下。问候 – user427969 2010-10-07 22:46:29
我编辑了我的答案,显示工作解决方案 – TheDarkIn1978 2010-10-08 01:46:53
您好,非常感谢,例如。一个小问题是,如果我们选择红色并开始在蓝色文本之间打字,那么写入的文本将是蓝色而不是红色。我发现了另一种方法。非常感谢你的帮助。问候 – user427969 2010-10-10 22:11:16