this.addEventListener(MouseEvent.MOUSE_DOWN,function(e:MouseEvent){this.startDrag(false,null);});
嗨,我想知道为什么上述不起作用?我试图在屏幕上拖动一个精灵。
在
舞台上创建一个精灵,添加实例名称框,将代码添加到第一帧:
box.addEventListener(MouseEvent.MOUSE_DOWN, startMove);
function startMove(evt:MouseEvent):void {
box.startDrag();
}
box.addEventListener(MouseEvent.MOUSE_UP, stopMove);
function stopMove(e:MouseEvent):void {
box.stopDrag();
}
我认为您的示例不起作用,因为事件侦听器处理程序中"this"的范围。
如果你删除this.
;它将起作用。这是一个范围问题,因为您使用匿名函数。您可以使用事件的currentTarget
,如果您添加相同的侦听器,这允许您使其他框也可以拖动。
注意:很难删除作为事件侦听器的匿名函数,并且可能导致内存泄漏,因此最好的方法是使用对命名函数的引用:
box.addEventListener(MouseEvent.MOUSE_DOWN, handleMouseEvent);
box.addEventListener(MouseEvent.MOUSE_UP, handleMouseEvent);
function handleMouseEvent(event:MouseEvent):void
{
switch(event.type)
{
case MouseEvent.MOUSE_DOWN:
{
DisplayObject(event.currentTarget).startDrag();
break;
}
case MouseEvent.MOUSE_UP:
{
DisplayObject(event.currentTarget).stopDrag();
break;
}
}
}