开发者

Is there a way to keep an object always at the top of the display list?

Is there a way to make a display object always be at the top of the display list?

For example, I know you can set the childIndex, i.e:

setChildIndex(myDisplayObject, numChildren-1);

But is 开发者_JAVA技巧there a way that an object has sensed that something else has been added to the display list and restack themselves accordingly?


You can listen to the Event.ADDED event on the container. This event will bubble up, so you'll get called whenever a display object is added to the container or any of its children.

Here's an example of how you could do this. You'll see the black box always stays on top.

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);

However, I think it's much simpler and cleaner just to have 2 containers, say, top and bottom, kind of like layers. In top you'd add the element that always must be on top (or this could be your element as you probably don't need to have this extra container). In bottom you'd add and remove whatever you want. Then you can forget about manually restacking stuff (at least to keep the top element atop).


You can override the addChild() method in the parent object. In that method you can move your child to the top using

setChildIndex(myDisplayObject, numChildren-1);

In this way everytime an object is added to the parent, the parent moves your object to the top.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜