0

我试图实现以下目标,但使用以下代码失败:

  1. 单击鼠标一次以显示该框。
  2. 再次单击它以消失该框。

发生的事情是,当我触发 mouse.click 事件(通过单击)时,它也触发了“stage.addEventListener(MouseEvent.CLICK, boxGone)”事件侦听器。在屏幕上没有发生任何事情,因为我在技术上 addChild 和 removeChild 框在同一帧。

我猜我的初始点击同时创建并触发了事件监听器。有没有办法在不改变触发事件(鼠标点击)的情况下避免这种情况发生?下面是代码:

public function ClassConstructor(){
 addEventListener(MouseEvent.CLICK, onMouseClickHandler);
}

private function onMouseClickHandler(e:MouseEvent):void{

 box.x = stage.mouseX;
 box.y = stage.mouseY;
 box.gotoAndPlay(1);

 stage.addChild(box);
 stage.addEventListener(MouseEvent.CLICK, boxGone);

}

private function boxGone(e:MouseEvent):void{
 stage.removeChild(box);
 stage.removeEventListener(MouseEvent.CLICK, boxGone);
}

在此先感谢,阳光

4

1 回答 1

1

Modify your first listener with:

stage.addEventListener(MouseEvent.CLICK, onMouseClickHandler);

The event goes from your main class to the stage, and you add the second listener in between, so it is called just after the function's closure. Another solution, to be sure, would be to call

e.stopImmediatePropagation();

This prevents any listener to catch the same event.

于 2013-06-05T15:24:59.743 回答