as(ActionScript)拖动实现

今天用as做了过一个最简单的拖动,代码没有任何的复杂性,添加了详细的注释,只要有as基础的都能直接看懂。

 

完整代码如下:

 

package

{

	import flash.display.DisplayObject;

	import flash.display.Sprite;

	import flash.events.MouseEvent;

	

	public class drag extends Sprite

	{

		//拖动对象一

		private var box:Sprite;

		//拖动对象二

		private var box2:Sprite;

		

		//鼠标在拖动对象内的偏移量

		private var offsetX:Number;

		private var offsetY:Number;

		//拖动的对象

		private var dragObject:DisplayObject;

		

		public function drag()

		{

			//实例拖动对象一

			box = new Sprite();

			box.graphics.beginFill(0xff0000);

			box.graphics.drawRect(100,100,50,50);

			box.graphics.endFill();

			this.addChild(box);

			//实例拖动对象二

			box2 = new Sprite();

			box2.graphics.beginFill(0x0000ff);

			box2.graphics.drawRect(155,155,50,50);

			box2.graphics.endFill();

			this.addChild(box2);

			//给拖动对象注册拖动事情

			box.addEventListener(MouseEvent.MOUSE_DOWN,dragStart);

			box2.addEventListener(MouseEvent.MOUSE_DOWN,dragStart);

			//舞台事件,用于移除拖动对象事件

			stage.addEventListener(MouseEvent.MOUSE_UP,dragStop);

		}

		//开始拖动

		private function dragStart(e:MouseEvent):void

		{

			//获得拖动的目标对象

			dragObject = e.target as DisplayObject;

			//记录偏移量

			offsetX = e.localX; // e.stageX - dragObject.x; 

			offsetY = e.localY; // e.stageY - dragObject.y;

			//把目标对象设置在舞台的最顶端

			stage.addChild(dragObject);

			//舞台事件,注册鼠标移动事件

			stage.addEventListener(MouseEvent.MOUSE_MOVE,dragging);

			

		}

		//拖动方法

		private function dragging(e:MouseEvent):void

		{

			//设置拖动目标对象的位置

			dragObject.x = e.stageX-offsetX;

			dragObject.y = e.stageY-offsetY;

		}

		//停止拖动

		private function dragStop(e:MouseEvent):void

		{

			//除多拖动事件

			stage.removeEventListener(MouseEvent.MOUSE_MOVE,dragging);

		}

	}

}

 

你可能感兴趣的:(actionscript)