Actionscript 3中如何控制实例的上下位置

在以前的版本中,使用getNextHighestDepth(), swapDepths(), getDepth()进行影片深度的管理与设置。在Flash9出来后,ActionScript也改变了,影片剪辑或说Display Object(ActionScript 3.0中的DisplayObject包括:Bitmap, Shape, Sprite, MovieClip, Video, TextField, Loader。这些除了Sprite,其他的类都可以被显示在stage中)通过addChild()与addChildAt()作为子元素被添加到Display List中,display list以数组的形式来管理它子元素,而addChild()或addChildAt()操作的Display Object被添加在数组的最后面–犹如通过push()操作数组一样–并显示在当前Container(容器)或Display Object(某些Display Object也可当作容器)里的最上层。
[codes=java]
package {
    import flash.display.MovieClip;
    import flash.text.TextField;

    public class example extends MovieClip {
        private var mc1 : MovieClip;
        private var mc2 : MovieClip;

        function example () {
            mc1 = new MovieClip();
            mc2 = new MovieClip();

            var tf1 : TextField = new TextField();
            tf1.text = ‘example1’;
            mc1.x = 100;
            mc1.y = 100;
            mc1.addChild(tf1);
            this.addChild(mc1);

            var tf2 : TextField = new TextField();
            tf2.text = ‘example2’;
            mc2.x = 105;
            mc2.y = 105;
            mc2.addChild(tf2);
            this.addChild(mc2);
        }
    }
}

这里创建了两个MC,并为他们各自创建了一个文本对象。如何操作他们之间的层次关系了,比如,单击mc1让他显示在mc2之上,反之亦然。可以这样:
[codes=java]
package {
    import flash.display.MovieClip;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
    // 引入事件类
    import flash.events.MouseEvent;

    public class example extends MovieClip {
        private var mc1 : MovieClip;
        private var mc2 : MovieClip;

        function example () {
            mc1 = new MovieClip();
            mc2 = new MovieClip();

            var tf1 : TextField = new TextField();
            tf1.text = ‘example1’;
            tf1.textColor = 0xffffff;
            tf1.autoSize = TextFieldAutoSize.LEFT;
            mc1.x = 100;
            mc1.y = 100;
            mc1.addChild(tf1);
            this.addChild(mc1);
            mc1.addEventListener(MouseEvent.CLICK, mc1_click);

            var tf2 : TextField = new TextField();
            tf2.text = ‘example2’;
            tf2.autoSize = TextFieldAutoSize.LEFT;
            mc2.x = 105;
            mc2.y = 105;
            mc2.addChild(tf2);
            this.addChild(mc2);
            mc2.addEventListener(MouseEvent.CLICK, mc2_click);
        }

        // 设置mc1显示在最顶层
        private function mc1_click (me : MouseEvent) : void {
            setChildIndex(mc1, this.numChildren – 1);
        }

        // 设置mc2显示在最顶层
        private function mc2_click (me : MouseEvent) : void {
            setChildIndex(mc2, this.numChildren – 1);
        }
    }
}

通过setChildIndex()设置影片剪辑,其他的影片剪辑对象会自动排列他们自己在Display List中的位置。可通过swapChildren(mc1, mc2)来置换mc1与mc2之间的层次,通过removeChild()移除指定Display Object,通过removeChildAt()移除指定位置的Display Object,通过getChildAt()获得指定索引的Display Object,通过getChildByName()获得指定名称的Display Object,通过getChildIndex()获得指定索引的Display Object。

发表评论