用laya开发时,策划提出需求,要修改特效的显示层级。注意,这次要修改层级的特效,并不是本来就在父容器上的,而是后来手动添加的,之前做的修改层级都是直接修改子元素的层级,直接修改zorder就完事了。之前已经做过类似的调整层级的问题,上来直接就用_zorder,结果发现,项目运行后,控制台的层级数据是正确的,但是显示出来的层级存在问题,手动修改控制台的zorder后,显示效果被刷新,显示效果达到预期效果。猜想可能是设置层级之后,没有进行层级刷新,查laya API,得到updatezorder,根据zOrder进行重新排序,添加到代码中之后,表现达到预期。
验证后,发现确实如此,addChild添加的元素会默认显示在最顶层。至于原因,addChild方法添加的子元素会被显示在最顶层。
Node类addChild()方法源码如下,arr用的push添加node ,直接添加到最上层显示
/**
* 添加子节点。
* @param node 节点对象
* @return 返回添加的节点
*/
public function addChild(node:Node):Node {
if (!node || destroyed || node === this) return node;
if (Sprite(node).zOrder) _set$P("hasZorder", true);
if (node._parent === this) {
var index:int = getChildIndex(node);
if (index !== _childs.length - 1) {
this._childs.splice(index, 1);
this._childs.push(node);
if (conchModel) {
conchModel.removeChild(node.conchModel);
conchModel.addChildAt(node.conchModel, this._childs.length - 1);
}
_childChanged();
}
} else {
node.parent && node.parent.removeChild(node);
this._childs === ARRAY_EMPTY && (this._childs = []);
//这里用的push,直接添加到最上层
this._childs.push(node);
conchModel && conchModel.addChildAt(node.conchModel, this._childs.length - 1);
node.parent = this;
_childChanged();
}
return node;
}
layabox的显示对象在舞台上显示之前,还需要有一个过程,那就是先添加到显示列表中。显示列表的作用就是将显示对象进行数据索引,用于层级的显示顺序(后添加的在最上层显示),然后在舞台上显示。所以,addChild添加的子元素会被显示在最顶层,
updatezorder之后,就能显示为预期的层级顺序了