[Flash&ActionScript]事件傾聽者_addEventListener(eventType,function)。範例:使用拖曳滑鼠繪出矩形,並可以進行拖動。
1: import flash.events.MouseEvent;
2: import flash.geom.Point;
3: import flash.display.Sprite;
4:
5: //兩個變數用來存放滑鼠點下、放開的位置
6: var startPoint:Point = new Point();
7: var endPoint:Point = new Point();
8: //滑鼠按下 "使用者自行繪出的矩型"設定為可拖曳
9: function rectMouseDown(event:MouseEvent):void
10: {
11: (event.currentTarget as Sprite).startDrag(false,null);
12: }
13: //滑鼠放開 "使用者自行繪出的矩型"設定為停止拖曳
14: function rectMouseUp(event:MouseEvent):void
15: {
16: (event.currentTarget as Sprite).stopDrag();
17: }
18: //繪圖
19: function DrawRect(points:Array):void
20: {
21: var _posX,_posY:int;
22: var _height,_width:uint;
23: if (points[0].x < points[1].x)
24: {
25: _posX = points[0].x;
26: }
27: else
28: {
29: _posX = points[1].x;
30: }
31: if (points[0].y < points[1].y)
32: {
33: _posY = points[0].y;
34: }
35: else
36: {
37: _posY = points[1].y;
38: }
39: _height = Math.abs(points[0].y - points[1].y);
40: _width = Math.abs(points[0].x - points[1].x);
41:
42: var rect:Sprite = new Sprite();
43: rect.graphics.beginFill(0x00ff00,1);
44: rect.graphics.drawRect(_posX,_posY,_width,_height);
45: rect.graphics.endFill();
46: rect.addEventListener(MouseEvent.MOUSE_DOWN,rectMouseDown);
47: rect.addEventListener(MouseEvent.MOUSE_UP,rectMouseUp);
48: this.addChild(rect);
49: }
50: //按下 記錄滑鼠起始位置
51: function MouseDown(event:MouseEvent):void
52: {
53: startPoint.x = this.mouseX;
54: startPoint.y = this.mouseY;
55: }
56: //放開 記錄滑鼠最終位置
57: function MouseUp(event:MouseEvent):void
58: {
59: endPoint.x = this.mouseX;
60: endPoint.y = this.mouseY;
61: //若事件的目標==舞台,才進行繪圖
62: if (event.target == stage)
63: {
64: DrawRect([startPoint,endPoint]);
65: }
66: }
67: //為場景加入兩個事件滑鼠按下、放開
68: this.parent.addEventListener(MouseEvent.MOUSE_DOWN,MouseDown);
69: this.parent.addEventListener(MouseEvent.MOUSE_UP,MouseUp);