ActionScript拖动元件

方法1:需要计算坐标

package 
{
	import flash.display.Sprite;
	import flash.display.MovieClip;
	import flash.events.MouseEvent;

	public class Main extends Sprite
	{
		private var white:uint = 0xffffff;
		private var black:uint = 0x000000;
		//鼠标在拖动对象内的偏移量
		private var offsetX:Number;
		private var offsetY:Number;
		//拖动元件
		private var mc:MovieClip;
		public function Main()
		{
			mc=new MovieClip();
			mc.graphics.lineStyle(2,black);
			mc.graphics.beginFill(white);
			mc.graphics.drawRect(100,100,30,30);
			mc.graphics.endFill();
			mc.addEventListener(MouseEvent.MOUSE_DOWN, dragStart);
			stage.addChild(mc);
			stage.addEventListener(MouseEvent.MOUSE_UP, dragStop);

		}
		//按下鼠标,开始拖动对象
		private function dragStart(e:MouseEvent):void
		{
			offsetX = e.localX;
			offsetY = e.localY;
			stage.addEventListener(MouseEvent.MOUSE_MOVE, dragging);
		}
		//拖动鼠标
		private function dragging(e:MouseEvent):void
		{
			mc.x = e.stageX - offsetX;
			mc.y = e.stageY - offsetY;
		}
		//停止拖动
		private function dragStop(e:MouseEvent):void
		{
			stage.removeEventListener(MouseEvent.MOUSE_MOVE, dragging);
		}
	}
}

方法2:非常简单

package 
{
	import flash.display.Sprite;
	import flash.display.MovieClip;
	import flash.events.MouseEvent;

	public class Main extends Sprite
	{
		private var white:uint = 0xffffff;
		private var black:uint = 0x000000;
		//拖动元件
		private var mc:MovieClip;
		public function Main()
		{
			mc=new MovieClip();
			mc.graphics.lineStyle(2,black);
			mc.graphics.beginFill(white);
			mc.graphics.drawRect(100,100,30,30);
			mc.graphics.endFill();
			mc.addEventListener(MouseEvent.MOUSE_DOWN, dragStart);
			mc.addEventListener(MouseEvent.MOUSE_UP, dragStop);
			mc.addEventListener(MouseEvent.MOUSE_MOVE,dragging);
			stage.addChild(mc);

		}
		//按下鼠标,开始拖动对象
		private function dragStart(e:MouseEvent):void
		{
			e.target.startDrag();
		}
		//拖动鼠标
		private function dragging(e:MouseEvent):void
		{
			e.updateAfterEvent();
		}
		//停止拖动
		private function dragStop(e:MouseEvent):void
		{
			e.target.stopDrag();
		}
	}
}


你可能感兴趣的:(拖动,actionscript)