添加或移除

在介绍 Container 时,已经了解到简单添加的姿势,或许这种简单的方式在有些场景下远远不够用,当然,你可以使用本篇介绍的更多的姿势。

添加到指定层

是的,用 addChildAt 方法,它接受两个参数:

addChildAt(child[DisplayObject], index[Number]);
// 先添加两个占位
container.addChild(new Tiny.Text('111111'));
container.addChild(new Tiny.Text('222222'));
// 再把精灵添加到 1 位置(即第 2 层)
container.addChildAt(Tiny.Sprite.fromImage('https://gw.alipayobjects.com/as/g/tiny/resources/1.0.0/images/ants/lamp.png'), 1);
console.log(container.children.length);
//=> 3

效果如下:

可以看出,文本 222222 被“挤”到第 3 层了,就是说,从插入位置起,后面的层次都 +1。

注意

addChildAt 的第二个参数不能超出子元素的总数,如果超出,会抛异常

移除

那么,如何移除场景里的精灵?可以使用 Container 类的 removeChild 方法,它接受一个参数:

removeChild(child[DisplayObject]);
container.removeChild(sprite);

但是,建议设置精灵的 visible 属性为 false,因为这样更简单,效率更高。

sprite.setVisible(false);

移除指定层

是的,用 removeChildAt 方法,它接受一个参数:

removeChildAt(index[Number]);
// 先添加两个占位
container.addChild(new Tiny.Text('111111'));
container.addChild(new Tiny.Text('222222'));
container.removeChildAt(1);
console.log(container.children.length);
//=> 1

然后,文本 222222 就被移除掉了。

批量移除

使用 removeChildren 可以批量移除多个连续相邻的显示对象,它接受两个参数:

removeChildren(beginIndex[Number=0], endIndex[Number=null]);

也就是起始位置,假设某个容器有4个精灵,我们想移除中间两个:

var container = new Tiny.Container();
// 循环添加
for (var i = 0; i < 4; i++) {
  container.addChild(Tiny.Sprite.fromImage('https://gw.alipayobjects.com/as/g/tiny/resources/1.0.0/images/hao/hao' + i + '.png'));
}
console.log(container.children.length);
//=> 4
// 移除2、3位
container.removeChildren(1, 3);
console.log(container.children.length);
//=> 2

监听变化

无论添加、交换还是移除精灵,都可以反馈出来,你可以通过监听 onChildrenChange 来做回调:

// 在操作前添加监听回调
container.onChildrenChange = function () {
  console.log('有人动你娃啦');
};
container.removeChildren();
//=> 有人动你娃啦