1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
| package
{
import flash.display.Sprite;
import flash.display.DisplayObject;
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.filters.DropShadowFilter;
public class ClassDrag extends Sprite
{
private var _red:Sprite;
private var _blue:Sprite;
private var _green:Sprite;
private var _white:Sprite;
// 被拖动对象原始坐标
private var _startingLocation:Point;
// 构造函数
public function ClassDrag()
{
init();
}
// 初始化
private function init():void
{
_red = new Sprite();
createRectangle(_red, 0xff0000, 10, 10, 20, 20);
_blue = new Sprite();
createRectangle(_blue, 0x0000ff, 10, 35, 20, 20);
_green = new Sprite();
createRectangle(_green, 0x00cc00, 10, 60, 20, 20);
_white = new Sprite();
createRectangle(_white, 0xf0f0f0, 40, 10, 300, 300, false);
}
// 创建矩型
private function createRectangle(rectangle:Sprite, color:uint, x:uint, y:uint, width:uint, height:uint, drag:Boolean = true):void
{
rectangle.graphics.beginFill(color);
rectangle.graphics.drawRect(x, y, width, height);
rectangle.graphics.endFill();
addChild(rectangle);
if(drag)
{
// 侦听事件
rectangle.addEventListener(MouseEvent.MOUSE_DOWN, pickup);
rectangle.addEventListener(MouseEvent.MOUSE_UP, place);
}
}
// 拖动
private function pickup(event:MouseEvent):void
{
// 保存原始坐标
_startingLocation = new Point();
_startingLocation.x = event.target.x;
_startingLocation.y = event.target.y;
// 开始拖动
event.target.startDrag();
// 加上阴影
event.target.filters = [new DropShadowFilter()];
// 拖动对象最前显示
setChildIndex(DisplayObject(event.target), numChildren - 1);
}
// 拖动结束
private function place(event:MouseEvent):void
{
// 拖动结束
event.target.stopDrag();
// 清除阴影
event.target.filters = null;
// 检测是否已经移动到目标区域
if(event.target.dropTarget == _white)
{
var color:uint;
switch(event.target)
{
case _red: color = 0xff0000; break;
case _blue: color = 0x0000ff; break;
case _green: color = 0x00cc00; break;
}
// 重新创建目标区域
_white.graphics.clear();
createRectangle(_white, color, 40, 10, 300, 300, false);
}
// 拖放对象回到原位
event.target.x = _startingLocation.x;
event.target.y = _startingLocation.y;
}
}
} |