Change format of any selected textfield in AS3?

后端 未结 1 968
梦毁少年i
梦毁少年i 2021-01-26 02:56

I create several textfields when the click event is fired. Now I want to change the text format of any selected textfield. But the format is just applied to the last created tex

相关标签:
1条回答
  • 2021-01-26 03:52

    It is right, because the variable myText refers to the last Object.

    Instead of this you can get the current TextField object from the Event. Each event has currentTarget value, which refers to the Object that has fired the Event. You then can cast the currentTarget to your type and do the action with it.

    Unfortunately I don't have your whole code, that is why I have my own version. Have a look at it, I think it can help you.

    //Main.as

    package
    {
    import flash.display.MovieClip;
    import flash.display.Sprite;
    import flash.events.MouseEvent;
    import flash.text.TextField;
    import flash.text.TextFormat;
    
    public class Main extends Sprite
    {
        private var button:Sprite;
        private var p:int = 50;
        private var x0:int = 20;
    
        public function Main()
        {
            init();
        }
    
        private function init():void
        {
            button = new Sprite();
    
            button.graphics.beginFill(0xFFCC00);
            button.graphics.drawRect(0, 0, 80, 20);
            button.graphics.endFill();
    
            button.addEventListener(MouseEvent.CLICK, onBtnClick);
    
            this.addChild(button);
        }
    
        private function onBtnClick(e:*):void
        {
            var myFormat:TextFormat = new TextFormat();
    
            var myText:TextField = new TextField();
            var mc3:MovieClip = new MovieClip();
            myText.text = "text...";
            myFormat.font = "Arial";
            myFormat.color = 0x000000;
            myText.setTextFormat(myFormat);
    
            mc3.addChild(myText);
    
            addChild(mc3);
            mc3.x = x0;
            mc3.y = p;
    
            p= mc3.y+mc3.height+10;
    
            myText.addEventListener(MouseEvent.CLICK, onTextClick)
        }
    
        private function onTextClick(evt:MouseEvent):void
        {
            var newFormat:TextFormat = new TextFormat();
            newFormat.size = 30;
            newFormat.font = "Verdana";
            (evt.currentTarget as TextField).setTextFormat(newFormat);
        }
    }
    }
    
    0 讨论(0)
提交回复
热议问题