/** * Toast 控制器 */ cc.Class({ extends: cc.Component, properties: { itemPrefab: cc.Prefab, _holdTime: 2, _showTime: 0.2, _hideTime: 0.3, _totalHeight: 0 }, /** * 添加一个Toast * * @author Pyden * @date 2019-03-22 * @param {string} msg Toast内容(支持富文本) * @param {float} holdTime 停留时长(秒)。默认是2秒 */ addToast (msg, holdTime, cb) { holdTime = holdTime || this._holdTime; let itemNode = cc.instantiate(this.itemPrefab); let toastItem = itemNode.getComponent('JMToastItem'); toastItem.msg = msg; this._showItem(itemNode, holdTime, cb); }, /** * 展示一个Toast * * @author Pyden * @date 2019-03-22 * @param {cc.Node} itemNode * @param {float} holdTime 停留时长(秒) */ _showItem (itemNode, holdTime, cb) { // toastRoot向上移动 let itemHeight = itemNode.height; // 总高度 this._totalHeight = this._totalHeight + itemHeight; this.node.stopAllActions(); cc.tween(this.node) .to(this._showTime, {position: cc.v2(0, this._totalHeight - itemHeight / 2)}) .start(); // 节点一直往下排列 itemNode.y = -this._totalHeight + itemHeight / 2; this.node.addChild(itemNode); itemNode.opacity = 0; cc.tween(itemNode) .to(this._showTime, {opacity: 255}) // 淡出 .delay(holdTime) // 停留 .to(this._hideTime, {opacity: 0}) // 淡出 .call(() => { itemNode.destroy(); // 销毁 if (cb) { cb(); } }).start(); } });