代码之家  ›  专栏  ›  技术社区  ›  redconservatory

有没有办法使对象始终位于显示列表的顶部?

  •  0
  • redconservatory  · 技术社区  · 15 年前

    是否有方法使显示对象始终位于显示列表的顶部?

    例如,我知道您可以设置childIndex,即:

    setChildIndex(myDisplayObject,numChildren-1);

    但是,有没有一种方法可以让对象感觉到其他内容已添加到显示列表中,并相应地重新标记它们自己?

    2 回复  |  直到 15 年前
        1
  •  5
  •   Juan Pablo Califano    15 年前

    Event.ADDED 容器上的事件。此事件将弹出,因此每当将显示对象添加到容器或其任何子容器时,都将调用此事件。

    var container:DisplayObjectContainer = this; // this is a frame script but just change this line as necessary
    container.addEventListener(Event.ADDED,handleAdded,true);
    
    function handleAdded(e:Event):void {
        // this if tries to cover some edge cases, unlikely to happen in your code, from your description
        if(container == topElement.parent && container.numChildren > 0 && container.getChildIndex(topElement) != container.numChildren - 1) {
            container.setChildIndex(topElement,numChildren - 1);
        }
    }
    
    function getSprite(c:uint):Sprite {
        var sp:Sprite = new Sprite();
        sp.graphics.beginFill(c);
        sp.graphics.drawRect(0,0,100,100);
        sp.graphics.endFill();
        return sp;
    }
    
    var topElement:Sprite = getSprite(0);
    
    container.addChild(topElement);
    var sp:Sprite = getSprite(0xff0000);
    container.addChild(sp);
    sp.addChild(getSprite(0xff00));
    var sp2:Sprite = getSprite(0xff);
    container.addChild(sp2);
    

    不过,我觉得只有两个容器更简单更干净,比如说, top bottom ,有点像层。在 顶部 您将添加始终必须位于顶部的元素(或者这可能是您的元素,因为您可能不需要这个额外的容器)。在 底部

        2
  •  3
  •   wezzy    15 年前

    可以重写父对象中的addChild()方法。在这种方法中,您可以使用

    setChildIndex(myDisplayObject, numChildren-1);