有多个MovieClip将动态放置在舞台上。这些MovieClip被编码为按钮。我想弄清楚 - 当用户点击MovieClip时...找出用户点击的flash舞台上的哪个对象。
内部函数toggleClick我把trace语句:
trace("movieClip Instance Name = " + e.target.name);
在OUTPUT窗口中:
movieClip Instance Name = instance5
movieClip Instance Name = instance12
movieClip Instance Name = instance5
movieClip Instance Name = instance32
movieClip Instance Name = instance5
movieClip Instance Name = instance59
这似乎不是获取被点击的MovieClip名称的方法。
getChildByName()是这样做的吗?如果是这样,任何想法如何使用getChildByName()来获取被点击的MovieClip的名称?
答案 0 :(得分:7)
在向舞台添加按钮之前,您可以将其命名为
var myButton:MovieClip = new MovieClip();
myButton.name = 'button1';
或
var myButton:MovieClip = new MyButton(); //if you assigned a class name to your MovieClip
myButton.name = 'button1';
用你的例子你可以这样做:
var comp:Comp = new Comp();
var monitor:Monitor = new Monitor();
addItemButton( comp, "comp" , {x:100, y:200});
addItemButton( monitor, "monitor" , {x:30 , y:50} );
private function addItemButton(item:MovieClip , itemName:String , params:Object):void
{
item.addEventListener(MouseEvent.CLICK , clickHandler );
item.name = itemName;
// of course params is not necessary, just making a point of
// how to centralize your concerns
item.x = params.x;
items.y = params.y;
addChild( item);
}
private function clickHandler(event:MouseEvent):void
{
trace( "button clicked:" + event.currentTarget.name );
}
答案 1 :(得分:2)
在AS3中,当你动态创建一个MovieClip flash时,它会像你看到的那样只读一个实例名(例如instance12)。查找单击哪个movieclip的最佳方法是简单地使用MouseEvent的currentTarget / target(请参阅这两者之间的差异:http://www.wastedpotential.com/?p=10)。
你会像这样使用它:
var foo:MovieClip = new MovieClip();
foo.graphics.drawRect(0, 0, 100, 50);
stage.addChild(foo);
foo.addEventListener(MouseEvent.CLICK, clickHandler);
var bar:MovieClip = new MovieClip();
bar.graphics.drawRect(0, 0, 100, 50); bar.y = 100;
stage.addChild(bar);
bar.addEventListener(MouseEvent.CLICK, clickHandler);
//this function will set the x to 100 and the width to 50 of the clicked MovieClip
function clickHandler(e:MouseEvent):void
{
e.currentTarget.x = 100;
e.currentTarget.width = 50;
}