下面的代码使用这些方法建立了简单的拖动效果。有三个不同颜色的矩形,右边有个白色的矩形作为拖动的目标,当拖动左边的矩形到白色矩形上时,松开鼠标,白色矩形就会i改变相应颜色。
代码:
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 | package { import flash.display.Sprite; import flash.display.DisplayObject; import flash.events.MouseEvent; import flash.geom.Point; import flash.filters.DropShadowFilter; public class ColorDrop extends Sprite { private var _red:Sprite; private var _green:Sprite; private var _blue:Sprite; private var _white:Sprite; // 保存被拖动对象原始坐标 private var startingLocation:Point; // 创建矩形和添加事件 public function ColorDrop( ) { createRectangles( ); addEventListeners( ); } private function createRectangles( ):void { _red = new Sprite( ); _red.graphics.beginFill( 0xFF0000 ); _red.graphics.drawRect( 0, 10, 10, 10 ); _red.graphics.endFill( ); _green = new Sprite( ); _green.graphics.beginFill( 0x00FF00 ); _green.graphics.drawRect( 0, 30, 10, 10 ); _green.graphics.endFill( ); _blue = new Sprite( ); _blue.graphics.beginFill( 0x0000FF ); _blue.graphics.drawRect( 0, 50, 10, 10 ); _blue.graphics.endFill( ); _white = new Sprite( ); _white.graphics.beginFill( 0xFFFFFF ); _white.graphics.drawRect( 20, 10, 50, 50 ); _white.graphics.endFill( ); addChild( _red ); addChild( _green ); addChild( _blue ); addChild( _white ); } private function addEventListeners( ):void { _red.addEventListener( MouseEvent.MOUSE_DOWN, pickup ); _red.addEventListener( MouseEvent.MOUSE_UP, place ); _green.addEventListener( MouseEvent.MOUSE_DOWN, pickup ); _green.addEventListener( MouseEvent.MOUSE_UP, place ); _blue.addEventListener( MouseEvent.MOUSE_DOWN, pickup ); _blue.addEventListener( MouseEvent.MOUSE_UP, place ); } public 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 ); } public 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 _green : color = 0x00FF00; break; case _blue : color = 0x0000FF; break; } _white.graphics.clear( ); _white.graphics.beginFill( color ); _white.graphics.drawRect( 20, 10, 50, 50 ); _white.graphics.endFill( ); } // 把被拖动对象放回原位 event.target.x = startingLocation.x; event.target.y = startingLocation.y; } } } |